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 WITH NOT MATCH?"

+4
source share
3 answers

Default. does not match line breaks. You will need to add a regex parameter so that it:

 Pattern p = Pattern.compile(myPattern,Pattern.DOTALL); 
+6
source

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

+3
source

First, as the arc said. will not match \ n unless you activate Pattern.DOTALL, but like Petter M, you must use m.find (), otherwise it will not match.

Then you can use this other expression if for some reason you cannot work with Pattern.DOTALL.

FILES_SECTION (: |?. \ S) * FILES_SECTION

(Note: I am using a non-capturing group for characters between FILES_SECTION delimiters).

+1
source

Source: https://habr.com/ru/post/1400024/


All Articles