Reputation: 57
Suppose i have a string kk a.b.cjkmkc jjkocc a.b.c.
I want to find the substring a.b.c
in the string , but it is not working.
Here is my code
Pattern p = Pattern.compile("a.b.c");
Matcher m = p.matcher(str);
int x = m.find()
Upvotes: 1
Views: 79
Reputation: 48434
The .
in Java Pattern
is a special character: "Any character (may or may not match line terminators)" (from the java.util.regex.Pattern
web page).
Try escaping it:
Pattern p = Pattern.compile("a\\.b\\.c");
Also note:
Matcher.find
returns boolean
, not int
.Pattern
s take double escapesUpvotes: 6
Reputation: 17028
As others have mentioned, .
is a special charater in regular expressions. You can let Java quote sepcial characters using Pattern.quote. BTW: What about String.indexof(String) (which is faster). if you really need regular expressions, have a look at this:
String str = "kk a.b.cjkmkc jjkocc a.b.c.";
Pattern p = Pattern.compile(Pattern.quote("a.b.c"));
Matcher m = p.matcher(str);
while (m.find()) {
int x = m.start();
// ...
}
Upvotes: 0