java - 正则表达式 - 需要帮助

标签 java regex pattern-matching

我有一个字符串模板,我需要从中获取#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/

相关文章:

java - Windows 2012 Server 用户锁定时 Camel 停止消费

javascript - 在间隔上使用正则表达式提取字符串 html

Haskell:编写一个函数来复制“elem”时陷入困境

java - 使用正则表达式获得最佳小组比赛

java - 带有自定义分隔符的 Spring AntPathMatcher 表现得很奇怪

java - 从抽象类层次结构中获取正确的字段?

java - 在java中解析Multipart/Mixed与Multipart/Alternative body

java - 如何更新 JTable

javascript - 在空格和引号上拆分字符串,保持带引号的子字符串完整

python - 在Python中使用re包将句子分成子句