0

Test site used : https://regex101.com/

Sample text

Tag [key=AccountAlias, value=MyAccount, tagDefinition=default-tag-definition]

RegEx 0 ( Non repeating )

(\w+) \[(.*)\]

Captures

Group 1.    0-3 `Tag`
Group 2.    5-76    `key=AccountAlias, value=MyAccount, tagDefinition=default-tag-definition`

Here , group1 captures a 'type', which here is 'Tag'

RegEx 1 ( Repeating )

((\w*)=([a-zA-Z-_0-9]+))

Captures

Match 1
Full match  5-21    `key=AccountAlias`
Group 1.    5-21    `key=AccountAlias`
Group 2.    5-8 `key`
Group 3.    9-21    `AccountAlias`
Match 2
Full match  23-38   `value=MyAccount`
Group 1.    23-38   `value=MyAccount`
Group 2.    23-28   `value`
Group 3.    29-38   `MyAccount`
Match 3
Full match  40-76   `tagDefinition=default-tag-definition`
Group 1.    40-76   `tagDefinition=default-tag-definition`
Group 2.    40-53   `tagDefinition`
Group 3.    54-76   `default-tag-definition`

Here Group2 captures an attribute of a type and Group3 captures value for the attribute.

Currently I am having to apply 2 regexs. How can RegEx 0 and RegEx 1 be combined to extract both "Type" and its attributes in one go.

If my combine my regex as

/(\w+) \[((\w*)=([a-zA-Z-_0-9]+))\]/g

Nothing matches, what is going wrong. A little explanation will help ..

7
  • What environment are you implementing this in? Commented Dec 19, 2018 at 22:27
  • You need the regex \G construct to do this in a single regex. Requires engine's PCRE, Php, Perl, etc.. The first match will be the tag and first key/value pair. Subsequent matches will be the key/pair, etc.. This may or may not be how you want to process it. It should have a callback if you need special array configurations.
    – user557597
    Commented Dec 19, 2018 at 22:41
  • Otherwise, the 2 step process works just as well.
    – user557597
    Commented Dec 19, 2018 at 22:45
  • If you use a regex with the \G construct to an array (without a callback), it would end up looking like ['tag1','key1=val1','','key2=vak2','tag2','key1=val1','','key2=val2','','key3=val3', etc...] which may not be what you want.
    – user557597
    Commented Dec 19, 2018 at 23:06
  • @WiktorStribiżew - The answer you have pointed to talks only about my RegEx 1 in my question. I can get that part working, but the combination of RegEx 0 and RegEx 1. Perhaps I am missing something , if so pointing to the same will help. Also, I am working on javascript Commented Dec 20, 2018 at 19:34

0

Browse other questions tagged or ask your own question.