1

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 $.

Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
user081608
  • 1,093
  • 3
  • 22
  • 48

2 Answers2

3

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

Andrew Sun
  • 4,101
  • 6
  • 36
  • 53
0

You can use Positive lookahead of Regular expression to search for .!? in front of a word. You can see this StackOverflow answer to learn more about Positive and Negative Lookaheads.

(\w+)(?=[.!?])

see this link

Use

Pattern.matches("(\\w+)(?=[.!?])]", "test! tset some ohter! wordsome?")

Matched Information

MATCH 1
1.  [0-4]   `test`
MATCH 2
1.  [16-21] `ohter`
MATCH 3
1.  [23-31] `wordsome`
Community
  • 1
  • 1
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71