Apps
Apps

Reputation: 3399

Regex for a non-greedy match

I've a String template which I need to process using regex. I need to get the list of #condition #endcondition 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.

Upvotes: 0

Views: 183

Answers (1)

Ian Henry
Ian Henry

Reputation: 22423

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.

Upvotes: 3

Related Questions