Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Android REGEX with Pattern and Matcher Classes?

I have the following code:

String example = "<!--§FILES_SECTION§\n" +
                "Example line one\n" +
                "Example line two\n" +
                "§FILES_SECTION§-->";

        String myPattern = ".*?FILES_SECTION.*?\n(.*?)\n.*?FILES_SECTION.*?";
        Pattern p = Pattern.compile(myPattern);
        Matcher m = p.matcher(example);

        if ( m.matches() )
            Log.d("Matcher", "PATTERN MATCHES!");
        else
            Log.d("MATCHER", "PATTERN DOES NOT MATCH!");

Why does it always return "PATTERN DOES NOT MATCH?"

like image 371
Davidoff Avatar asked Dec 28 '22 04:12

Davidoff


2 Answers

By default, the . does not match line breaks. You would need to add a regex option so that it does:

Pattern p = Pattern.compile(myPattern,Pattern.DOTALL);
like image 86
arc Avatar answered Dec 29 '22 18:12

arc


m.matches() will only return true if the entire string matches. Use m.find() instead, and it should work better!

like image 26
Petter Avatar answered Dec 29 '22 17:12

Petter