user081608 user081608 - 3 months ago 8
Java Question

Matching word with period at end in regex

Currently I am trying to see if there is a period, question mark or exclamation point at the end of a word in regex java. Here is what I'm trying:

if(Pattern.matches("[.!?]$", "test.")){
// do stuff
}


Here I am just using the example
test.
which is a word and has a period at the end. This regex will not pick it up. I am using this regex because it will look for the three
.!?
at the end of the sentence since I am using
$
.

Answer

Pattern.matches matches against the entire string. You can either modify your pattern, or use Matcher.find instead.

Option 1:

Pattern.matches(".*[.!?]", "test.")

Option 2:

Pattern.compile("[.!?]$").matcher("test.").find()