[英]How to replace last letter to another letter in java using regular expression
i have seen to replace "," to "." 我已经看到将“,”替换为“。” by using ".$"|",$", but this logic is not working with alphabets.
通过使用“。$”|“,$”,但这个逻辑不适用于字母表。 i need to replace last letter of a word to another letter for all word in string containing EXAMPLE_TEST using java this is my code
我需要将包含EXAMPLE_TEST的字符串中所有单词的单词的最后一个字母替换为另一个字母,这是我的代码
Pattern replace = Pattern.compile("n$");//here got the real problem
matcher2 = replace.matcher(EXAMPLE_TEST);
EXAMPLE_TEST=matcher2.replaceAll("k");
i also tried "//n$" ,"\\n$" etc Please help me to get the solution input text=>njan ayman output text=> njak aymak 我也试过“// n $”,“\\ n $”等请帮我搞定解决方案输入text => njan ayman output text => njak aymak
You can use lookahead and group matching: 您可以使用前瞻和组匹配:
String EXAMPLE_TEST = "njan ayman";
s = EXAMPLE_TEST.replaceAll("(n)(?=\\s|$)", "k");
System.out.println("s = " + s); // prints: s = njak aymak
Explanation: 说明:
(n) - the matched word character
(?=\\s|$) - which is followed by a space or at the end of the line (lookahead)
The above is only an example! 以上只是一个例子! if you want to switch every comma with a period the middle line should be changed to:
如果要将每个逗号切换为句点,则应将中间行更改为:
s = s.replaceAll("(,)(?=\\s|$)", "\\.");
Instead of the end of string $
anchor, use a word boundary \\b
而不是字符串
$
anchor的结尾,使用单词边界\\b
String s = "njan ayman";
s = s.replaceAll("n\\b", "k");
System.out.println(s); //=> "njak aymak"
Here's how I would set it up: 这是我如何设置它:
(?=.\\b)\\w
Which in Java would need to be escaped as following: 在Java中需要转义如下:
(?=.\\\\b)\\\\w
It translates to something like "a character (\\w) after (?=) any single character (.) at the end of a word (\\b)". 它转换为“字符(\\ w)之后(?=)单词(\\ b)末尾的任何单个字符(。)”。
String s = "njan ayman aowkdwo wdonwan. wadawd,.. wadwdawd;";
s = s.replaceAll("(?=.\\b)\\w", "");
System.out.println(s); //nja ayma aowkdw wdonwa. wadaw,.. wadwdaw;
This removes the last character of all words, but leaves following non-alphanumeric characters. 这将删除所有单词的最后一个字符,但会留下非字母数字字符。 You can specify only specific characters to remove/replace by changing the
.
您只能通过更改来指定要删除/替换的特定字符
.
to something else. 别的东西。
However, the other answers are perfectly good and might achieve exactly what you are looking for. 但是,其他答案非常好,可能完全符合您的要求。
if (word.endsWith("char oldletter")) {
name = name.substring(0, name.length() - 1 "char newletter");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.