我正在Kotlin应用程序中编写正则表达式,以匹配以下情况:用户将发送类似以下的字符串:
1. "{{example}}" -> match: example
2. "{{{example2}}}" -> match: example2
3. "{{example3}}}" -> do not match
4. "{example4}" -> do not match
5. "{{{example5}}" -> do not match
6. "{{{{example6}}}}" -> do not match
7. "{{ example7 }} some other words {{{example8}}}" -> match: example7 and example8
8. "{{{example9}}} some other words {{example10}} {{example11}}" -> match: example9, example10 and example 11
因此,要匹配两个或恰好三个花括号之间的单词。这是我接近结果的方法:
regex = \{{2}([^{^}]+)\}{2}([^}])|\{{3}([^{^}]+)\}{3}([^}])
这个正则表达式可以匹配除了example5以外的所有内容,你也可以在这里查看 https://regex101.com/r/M0kw3j/1
.*?
替换为[^\{\}]*
,以排除{{exam}ple}}
— 即(?<!\{)(?:\{\{[^\{\}]*\}\}|\{\{\{[^\{\}]*\}\}\})(?!\})
。我认为示例4没有任何问题。 - Amadan