1

I need to make pattern which will accept String in format (_,_) e.g: "(0,0)", "(1,3)", "(5,8)" etc.

I wrote condition as following:

if (name.equals("(\\d,\\d)")) {
   System.out.println("accepted")
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Yarh
  • 4,459
  • 5
  • 45
  • 95
  • `String#equals` does not use regular expressions. – Sotirios Delimanolis Apr 09 '14 at 00:18
  • As stated in the [Regex Wiki FAQ](http://stackoverflow.com/a/22944075/2736496), under "Flavor-specific meta-information" (third section from the bottom), the only `java.lang.String` functions that accept regular expressions are `matches(s)`, `replaceAll(s,s)`, `replaceFirst(s,s)`, `split(s)`, and `split(s,i)` – aliteralmind Apr 09 '14 at 00:32

2 Answers2

3

You need to escape the parenthesis with \. They have special meaning in regex (for grouping).

You also need to call the correct method, one which matches with a regex, which isn't equals(), but matches().

alex
  • 479,566
  • 201
  • 878
  • 984
1

name.equals() doesn't actually accept a regular expression. You're looking for matches(), which will accept a regular expression.

You'll also have to escape the parentheses, as they have special meaning in a regular expression.

if(name.matches("\\(\\d,\\d\\)") {
    System.out.println("accepted");
}
Makoto
  • 104,088
  • 27
  • 192
  • 230