user081608
user081608

Reputation: 1113

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

Upvotes: 2

Views: 7221

Answers (2)

Andrew Sun
Andrew Sun

Reputation: 4231

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

Upvotes: 4

Raman Sahasi
Raman Sahasi

Reputation: 31841

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`

Upvotes: 0

Related Questions