Darth.Vader
Darth.Vader

Reputation: 6271

pattern matching to detect special characters in a word

I am trying to identify any special characters ('?', '.', ',') at the end of a string in java. Here is what I wrote:

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("{.,?}$");
    Matcher matcher = pattern.matcher("Sure?");
    System.out.println("Input String matches regex - "+matcher.matches());

}

This returns a false when it's expected to be true. Please suggest.

Upvotes: 0

Views: 280

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

Try this

Pattern pattern = Pattern.compile(".*[.,?]");
...

Upvotes: 2

anubhava
anubhava

Reputation: 785058

This is your code:

Pattern pattern = Pattern.compile("{.,?}$");
Matcher matcher = pattern.matcher("Sure?");
System.out.println("Input String matches regex - "+matcher.matches());

You have 2 problems:

  1. You're using { and } instead of character class [ and ]
  2. You're using Matcher#matches() instead of Matcher#find. matches method matches the full input line while find performs a search anywhere in the string.

Change your code to:

Pattern pattern = Pattern.compile("[.,?]$");
Matcher matcher = pattern.matcher("Sure?");
System.out.println("Input String matches regex - " + matcher.find());

Upvotes: 2

sp00m
sp00m

Reputation: 48817

Use "sure?".matches(".*[.,?]").

String#matches(...) anto-anchors the regex with ^ and $, no need to add them manually.

Upvotes: 3

Related Questions