简体   繁体   中英

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

  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

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

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:

(?=.\\\\b)\\\\w

It translates to something like "a character (\\w) after (?=) any single character (.) at the end of a word (\\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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM