[英]Regex to match words inside two or three curly braces
我正在 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
使用alternation 和lookaround s,你可以使用这个正则表达式:
(?<!\{)(\{{3}[^{}\n]*}{3}|\{{2}[^{}\n]*}{2})(?!})
正则表达式详细信息:
(?<!\{)
:否定后向断言我们没有{
在以前的 position(
: 开始捕获组 #1
\{{3}
: 第 3 场比赛开场{{{
[^{}\n]*
: 匹配 0 个或多个不是{
和}
的任何字符}{3}
: 第 3 场比赛结束}}}
|
: 或 (交替)\{{2}
: 匹配 2 开头{{
[^{}\n]*
: 匹配 0 个或多个不是{
和}
的任何字符}{2}
: 第 2 场比赛结束}}
)
: 关闭捕获组 #1(?!})
: 否定前瞻断言我们在下一个 position 没有}
这可能对您有用:
(?<!\{)\{\{(?:([^{}]+)|\{([^{}]+)})}}(?!})
查看在线演示
(?<!\{)
- 打开花括号的负向后视。\{\{
- 两个文字大括号(左)。(?:
- 打开非捕获组。
([^{}]+)
- 持有 1+ 个非开/闭括号的第一个捕获组。|
- 或者:\{([^{}]+)}
- 带有前括号和尾括号的第二个捕获组。)
- 关闭非捕获组。}}
- 两个文字大括号(右)。(?!})
- 关闭大括号的负前瞻。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.