user3275944
user3275944

Reputation: 57

Find a subtring in a string using a regular expression

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

Answers (2)

Mena
Mena

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.
  • Patterns take double escapes

Upvotes: 6

steffen
steffen

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

Related Questions