简体   繁体   中英

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

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

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

First, as arc has said, . won't match to \\n unless you activate Pattern.DOTALL, and as Petter M, you should use m.find(), or else it won't match.

Then, you could use this other expression, if, by any reason, you cannot work with Pattern.DOTALL.

FILES_SECTION(?:.|\\s)*FILES_SECTION

(Note I'm using a non-capturing group for the characters between the FILES_SECTION delimiters).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM