Search code examples
javaregexletter

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


Solution

  • 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"