I've a String template which I need to process using regex. I need to get the list of #condition #en开发者_运维百科dcondition
blocks from the below template. I tried the following regular expression
String condition="\\#condition(.*)\\#endcondition";
But the below code
Pattern pattern=Pattern.compile( condition,Pattern.DOTALL);
Matcher matcher=pattern.matcher( template );
while(matcher.find()){
System.out.println("Found a match:[" + matcher.group()+"]");
}
The above system out prints everything from first #condition
to last #endcondition
. But I need to get two blocks. ie first matcher.find()
should find the first #if - #endif
block and second matcher.find()
should find the second #condition-#endcondition
.
The easiest way to do this is to use a lazy quantifier:
"#if(.*?)#endif"
Also #
is not a regex metacharacter so you don't need to escape it.
精彩评论