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 ..

sharadendu sinha
  • 827
  • 4
  • 10
  • What environment are you implementing this in? – CertainPerformance Dec 19 '18 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. –  Dec 19 '18 at 22:41
  • Otherwise, the 2 step process works just as well. –  Dec 19 '18 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. –  Dec 19 '18 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 – sharadendu sinha Dec 20 '18 at 19:34
  • @sln - Thanks for your response , but I would also want to capture "Tag" as one of the groups. – sharadendu sinha Dec 20 '18 at 19:40
  • `I am working on javascript` Then you have to do this in 2 steps. –  Dec 22 '18 at 00:30

0 Answers0