sdaau
sdaau

Reputation: 38619

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:

/{((?=\.\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*?, 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:

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

.. while I'd want an array of matches being (.aa1, .b3c. .f4). How can I achieve this?

Upvotes: 0

Views: 59

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

You may try the below positive lookahead based regex.

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

I assumed that the parenthesis must be closed properly.

DEMO

Upvotes: 2

Related Questions