'How to match a string's end using a regex pattern in Java?

I want a regular expression pattern that will match with the end of a string.

I'm implementing a stemming algorithm that will remove suffixes of a word.

E.g. for a word 'Developers' it should match 's'.
I can do it using following code :

Pattern  p = Pattern.compile("s");
Matcher m = p.matcher("Developers");
m.replaceAll(" "); // it will replace all 's' with ' '

I want a regular expression that will match only a string's end something like replaceLast().



Solution 1:[1]

You need to match "s", but only if it is the last character in a word. This is achieved with the boundary assertion $:

input.replaceAll("s$", " ");

If you enhance the regular expression, you can replace multiple suffixes with one call to replaceAll:

input.replaceAll("(ed|s)$", " ");

Solution 2:[2]

Use $:

Pattern p = Pattern.compile("s$");

Solution 3:[3]

    public static void main(String[] args) 
{
    String message = "hi this message is a test message";
    message = message.replaceAll("message$", "email");
    System.out.println(message);
}

Check this, http://docs.oracle.com/javase/tutorial/essential/regex/bounds.html

Solution 4:[4]

When matching a character at the end of string, mind that the $ anchor matches either the very end of string or the position before the final line break char if it is present even when the Pattern.MULTILINE option is not used.

That is why it is safer to use \z as the very end of string anchor in a Java regex.

For example:

Pattern p = Pattern.compile("s\\z");

will match s at the end of string.

See a related Whats the difference between \z and \Z in a regular expression and when and how do I use it? post.

NOTE: Do not use zero-length patterns with \z or $ after them because String.replaceAll(regex) makes the same replacement twice in that case. That is, do not use input.replaceAll("s*\\z", " ");, since you will get two spaces at the end, not one. Either use "s\\z" to replace one s, or use "s+\\z" to replace one or more.

If you still want to use replaceAll with a zero-length pattern anchored at the end of string to replace with a single occurrence of the replacement, you can use a workaround similar to the one in the How to make a regular expression for this seemingly simple case? post (writing "a regular expression that works with String replaceAll() to remove zero or more spaces from the end of a line and replace them with a single period (.)").

Solution 5:[5]

take a look for following example:

String ss = "Developers".replaceAll(".$", " ");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeff Holt
Solution 2 Jesper
Solution 3
Solution 4 Wiktor Stribiżew
Solution 5 Sumit Singh