NS studios
NS studios

Reputation: 167

How can I find all instances of a group in regexp?

I'm trying to capture all instances of text between < and > symbols, as well as the beginning word.

test <1> <example> <dynamic

I tried the following expression:

(\w+) (?:<(.*?)>)+

but it doesn't work. There can be 1 or more groups that I have to capture. What I expect this to capture is (groups): * test * 1 * example * dynamic

but all I get is: * test * 1

Can anyone help me figure out how to do this properly? Thanks a lot.

Upvotes: 2

Views: 611

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

Using pcre you could have 2 groups, where the fist group will match test from the start of the string and the second group will contain the values between the brackets.

The \G anchor will match either at the start of the string, or asserts the position at the end of the previous match.

At the start of the string, you will match 1+ word characters.

(?:(\w+)|\G(?!^))\h+<([^<>]+)>

Regex demo

Explanation

  • (?: Non capture group
    • (\w+) Capture group 1, match 1+ word chars
    • | Or
    • \G(?!^) Assert position at the end of previous match, not at the start
  • ) Close group
  • \h+ Match 1+ horizontal whitespace chars
  • <([^<>]+)> Match < Capture in group 2 any char other than < or > and match >

Upvotes: 3

Related Questions