2

Can anybody help with regular expression? This code work good.

public static void main(String[] args) {

    String s = "with name=successfully already exist\n";

    Pattern p = Pattern.compile(".+name=.*successfully.+", Pattern.DOTALL);
    java.util.regex.Matcher m = p.matcher(s);

    if (m.matches()) {
        System.out.println("match");
    } else {
        System.out.println("not match");
    }

}

But this code return "not match". Why?

public static void main(String[] args) {

    String s = "with name=successfully already exist\n";

    if (s.matches(".+name=.*successfully.+")) {
        System.out.println("match");
    } else {
        System.out.println("not match");
    }

}

2 Answers 2

5

The only difference between the two is the DOTALL flag in the first example.

Without that flag, the \n at the end of the string will not match the last pattern (.+).

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL

In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.

Note that matches tries to match the whole string (including in your case the trailing newline), not just try to find a substring (this is different in Java than from many other languages).

Sign up to request clarification or add additional context in comments.

Comments

4

The Pattern.DOTALL parameter you provide when using compile() makes it so that '.' matches 'end of line terminators'. You need to provide an inline tag to make matches() do the same. Try the following:

s.matches("(?s).+name=.*successfully(?s).+")

Cheers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.