Jeena
Jeena

Reputation: 17

How to write regular expression to match a pattern in java?

I've the following java string:

"Java (simple) _New=AB_U748490_JAVA47BYH"

.. and I'm using the following regular expression:

"_New=[A-Z]{2}_(\w{7})_(JAVA.+)";

Problem: it always returns false. But why?

Upvotes: 0

Views: 61

Answers (1)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

The way you have written your regex will work with Matcher.find() because find searches the regex in whole input string anywhere.

If you want to make your regex to match fully, you need to modify your regex little and prepend .* in the beginning of regex something like this,

.*_New=[A-Z]{2}_(\\w{7})_(JAVA.+)

Notice how in java you need to escape \ character to \\

Try with this code and it will print Matches

public static void main(String[] args) {
    String s = "Java (simple) _New=AB_U748490_JAVA47BYH";
    Pattern p = Pattern.compile(".*_New=[A-Z]{2}_(\\w{7})_(JAVA.+)");

    Matcher m = p.matcher(s);
    if (m.matches()) {
        System.out.println("Matches");
    } else {
        System.out.println("Didn't match");
    }
}

Or alternatively, you can use find() method on Matcher object if you don't want to change your regex.

Hope that helps.

Upvotes: 2

Related Questions