我有一个字符串模板,我需要从中获取#elseif block 的列表。例如第一个#elseif block 将来自
#elseif ( $variable2 )Some sample text after 1st ElseIf.
,第二个#elseif block 来自#elseif($variable2)这段文字可以重复多次直到调用do while。第二个 ELSEIF
等等。为此,我使用以下正则表达式。
String regexElseIf="\\#elseif\\s*\\((.*?)\\)(.*?)(?:#elseif|#else|#endif)";
但它只返回一个匹配项,即第一个#elseif block 而不是第二个。我还需要获得第二个#elseif block 。你能帮我做吗?请找到以下字符串模板。
String template =
"This is a sample document."
+ "#if ( $variable1 )"
+ "FIRST This text can be repeated many times until do while is called."
+ "#elseif ( $variable2 )"
+ "Some sample text after 1st ElseIf."
+ "#elseif($variable2)"
+ "This text can be repeated many times until do while is called. SECOND ELSEIF"
+ "#else "
+ "sample else condition "
+ "#endif "
+ "Some sample text."
+ "This is the second sample document."
+ "#if ( $variable1 )"
+ "SECOND FIRST This text can be repeated many times until do while is called."
+ "#elseif ( $variable2 )"
+ "SECOND Some sample text after 1st ElseIf."
+ "#elseif($variable2)"
+ "SECOND This text can be repeated many times until do while is called. SECOND ELSEIF"
+ "#else " + "SECOND sample else condition " + "#endif "
+ "SECOND Some sample text.";
最佳答案
这段代码
Pattern regexp = Pattern.compile("#elseif\\b(.*?)(?=#(elseif|else|endif))");
Matcher matcher = regexp.matcher(template);
while (matcher.find())
System.out.println(matcher.group());
会产生
#elseif ( $variable2 )Some sample text after 1st ElseIf.
#elseif($variable2)This text can be repeated many times until do while is called. SECOND ELSEIF
#elseif ( $variable2 )SECOND Some sample text after 1st ElseIf.
#elseif($variable2)SECOND This text can be repeated many times until do while is called. SECOND ELSEIF
secret 在于 positive lookahead (?=#(elseif|else|endif))
,所以#elseif
、#else
或#endif
将被匹配,但字符不会被消耗。这样他们就可以在下一次迭代中找到。
关于java - 正则表达式 - 需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3827613/