Edward
Edward

Reputation: 4651

Why do strings with newlines do not match regular expressions in Java?

I have a String string that contains a newline (\n). When I try to match it with a regular expression pattern it returns false, although there should be a match.

package com.stackoverflow;

public class ExgExTest {

    public static void main(String[] args) {
        String pattern = ".*[0-9]{2}[A-Z]{2}.*";
        String string  = "123ABC\nDEF";

        if (string.matches(pattern)) {
            System.out.println("Matches.");
        } else {
            System.out.println("Does not match.");
        }

    } // END: main()

} // END: class

How can I match multiline strings with a regular expression?

Upvotes: 2

Views: 136

Answers (2)

ivan.mylyanyk
ivan.mylyanyk

Reputation: 2101

You should use Pattern.quote(pattern) to escape all special characters in the pattern.

Documentation.

Upvotes: 0

anubhava
anubhava

Reputation: 786291

How can I match multiline strings with a regular expression?

You need to use DOTALL (s) flag for this:

String pattern = "(?s).*[0-9]{2}[A-Z]{2}.*";

Take note of (?s) which will make DOT match new lines also.

Upvotes: 3

Related Questions