How to accept any order of groups in regex?

Viewed 44

as already mentioned in my provider question, how can I change an regex with names capture groups from a dedicated order of the groups to any order is accepted?

As an example of my data:

{
  att1 = "demo1"
  att2 = "ohno"
}
{
  att2 = "demo1"
  att1 = "ohno"
}

If I use this regex, it will work for the first record but not for the second one

/\{[\n\s]*(?:att1 = \"(?<att1>\w*)\"[\n\s]*(?:att2 = \"(?<att2>\w*)\"[\n\s]*\}/gm

Connecting both groups with an | will not help. Instead it finds only the last group, but why?

/\{[\n\s]*(?:(?:att1 = \"(?<att1>\w*)\"[\n\s]*)|(?:(?:att2 = \"(?<att2>\w*)\"[\n\s]*)\}/gm

Test in online Tools do not really help because there the regex might work bot not in my local nodejs 16 version

1 Answers

You can use this regex:

/(?<=\{[^}]*?)(?:att1 = "(?<att1>\w*)"|att2 = "(?<att2>\w*)")(?=[^}]*?\})/g

Explanation:

(?<=\{[^}]*?) - look behind for { and zero or more character not being }, as few as possible.

(?: - create a non capturing group with an alternation

att1 = " - match att1 = " literally

(?<att1>\w*) - match and capture zero or more word characters.

"|att2 = " - match " OR àtt2 = "` literally

(?<att2>\w*)" - match and capture zero or more word characters and "

) - end group

(?=[^}]*?\}) - look ahead for zero or more characters not being } as few as possible and the final }

It must have the global flag.

Now it doesn't care about the order, but gets both.

Related