How to use Android REGEX with Pattern and Matcher Classes?

Davidoff picture Davidoff · Mar 6, 2012 · Viewed 18.3k times · Source

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?"

Answer

arc picture arc · Mar 6, 2012

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);