How to use Android REGEX with Pattern and Matcher Classes?

自闭症网瘾萝莉.ら 提交于 2019-12-07 06:58:15

问题


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


回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/9585859/how-to-use-android-regex-with-pattern-and-matcher-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!