gpt4 book ai didi

java - 不必要的长正则表达式

转载 作者:行者123 更新时间:2023-11-29 04:42:16 25 4
gpt4 key购买 nike

我尝试匹配这个字符串模式。它可以包含一些用两个花括号括起来的词。这些花括号必须格式正确且不能嵌套。

例如:

I have this {{example}} which is right
Here {{is}} another {{example}} which is right
{{ This {{ example }} is wrong }}
{{ This }}example {{ is also { wrong }}

我构建了这个似乎有效的正则表达式,但它很长,我认为它可以简化。

"^([^{}]*\\{\\{([^{}]*)\\}\\}[^{}]*)+$"

有什么办法可以简化这个吗?

最佳答案

进行否定匹配会更容易。即,查找不允许的内容:

\\{\\{[^}]*\\{

并使用Matcher.find() .由于使用 regex against XML is problematic 的相同原因,尝试通过正匹配来做到这一点很困难。 .

如果你想抓取大括号的内容,这就足够了

\\{\\{(\\w+\\)}\\}

关于java - 不必要的长正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38699926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com