开发者

Regex for a non-greedy match

开发者 https://www.devze.com 2023-01-18 15:14 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消