问题
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