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 (.
)").