简体   繁体   English

正则表达式迭代匹配多个单词

[英]Regex match multiple words iteratively

I have this test string: 我有这个测试字符串:

{.aa1 .b3c .f4}

I want to extract arbitrary number of words starting with literal dot . 我想提取任意数量的以文字点开头的单词. inside the braces. 大括号内。 So I wrote this JavaScript regex: 所以我写了这个JavaScript正则表达式:

/{((?=\.\w+?)(\.\w+?)\s*?)*}/g

I'm basically looking ahead (?=\\.\\w+?) , but if there's a match it isn't captured since lookahead is zero width, so then I capture (\\.\\w+?) , and then allow for possibility of spaces \\s*? 我基本上是在向前看(?=\\.\\w+?) ,但是如果有匹配项,因为前瞻宽度为零,所以不会捕获到匹配项,所以我捕获(\\.\\w+?) ,然后考虑空格\\s*? , and then I group all this, and try to iterate by repeating it with * . ,然后将所有这些分组,并尝试通过使用*重复进行迭代。 But it doesn't work - regex101.com tells me that returns: 但这不起作用-regex101.com告诉我返回:

MATCH 1
1.  `.f4`
2.  `.f4`

.. while I'd want an array of matches being ( .aa1 , .b3c . .f4 ). ..而我愿意匹配的阵列是( .aa1.b3c.f4 )。 How can I achieve this? 我该如何实现?

You may try the below positive lookahead based regex. 您可以尝试以下基于正向前瞻的正则表达式。

string.match(/\.\w+(?=[^{}]*\})/g)

I assumed that the parenthesis must be closed properly. 我认为必须正确关闭括号。

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM