正则表达式匹配两个或三个大括号内的单词
我正在 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})(?!})
更新的正则表达式演示
正则表达式详情:
(?<!{):否定后视断言我们{在前一个位置没有(:开始捕获组#1{{3}: 第 3 场比赛开场{{{[^{}n]*: 匹配 0 个或多个不为{和的任何字符}}{3}: 第 3 场比赛结束}}}|:或(交替){{2}:第2场开场{{[^{}n]*: 匹配 0 个或多个不为{和的任何字符}}{2}: 第 2 场比赛结束}}
): 关闭捕获组 #1(?!}):否定前瞻断言我们}在下一个位置没有
回答
这里有一些可能对你有用的东西:
(?<!{){{(?:([^{}]+)|{([^{}]+)})}}(?!})
看在线演示
- 正好在 2 个大括号之间的单词将在第 1 组中。
- 正好在 3 个大括号之间的单词将在第 2 组中。
(?<!{)- 打开花括号的负向后视。{{- 两个文字大括号(左)。(?:- 打开非捕获组。([^{}]+)- 持有 1+ 非开/关括号的第一个捕获组。|- 或者:{([^{}]+)}- 带有前导和尾随括号的第二个捕获组。)- 关闭非捕获组。
}}- 两个文字大括号(右)。(?!})- 关闭大括号的负前瞻。