Reputation: 6271
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
Reputation: 136002
Try this
Pattern pattern = Pattern.compile(".*[.,?]");
...
Upvotes: 2
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:
{ and }
instead of character class [ and ]
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
Reputation: 48817
Use "sure?".matches(".*[.,?]")
.
String#matches(...)
anto-anchors the regex with ^
and $
, no need to add them manually.
Upvotes: 3