Q:

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

A:

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|$)", "\\.");

A:

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"

