testing495
testing495

Reputation: 272

Dynamically naming captured groups in regex

I'm trying to name the captured groups of a long string based on a group previously matched. The keys and values matched all appear after the word info

For instance in this string: info user alice age seven I want to capture alice and name it user and capture seven and name it age.

The keys user and age are dynamic and could change each time, and I need that to be reflected accurately on the captured group's name.

essentially, I need to extend this regex to be dynamic. info\s(?<user>\w+\b)

Is this possible?

I'm aware there is a limitation on regex to have unlimited groups, so in this case, just assume there are only ever two groups that need to be matched

Upvotes: 2

Views: 631

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

Note: group names are static, they cannot be assigned at runtime.

You can only specify the group names inside the pattern, like

info\s+user\s+(?<user>\w+)\s+age\s+(?<age>\w+(?:-\w+)?)

See the regex demo. Details:

  • info\s+user\s+ - info string, then one or more whitespace, user, one or more whitespaces
  • (?<user>\w+) - Group "user": one or more word chars
  • \s+age\s+ - age enclosed with one or more whitespaces
  • (?<age>\w+(?:-\w+)?) - Group "age": one or more word chars and an optional occurrence of - and one or more word chars. Note the (?:-\w+)? is added to account for seventy-four or seventy-five, etc.

Upvotes: 2

Related Questions