Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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

like image 902
VishalDevgire Avatar asked Jan 16 '13 09:01

VishalDevgire


People also ask

How do you check if a string matches a regex in Java?

Variant 1: String matches() This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).

What is the use of \\ in Java?

The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.


1 Answers

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)$", " ");
like image 104
Marko Topolnik Avatar answered Oct 12 '22 07:10

Marko Topolnik