Reputation: 3405
Text:
Name=Jennifer,Age=29,Height=1.70,Occupation=Actress...
Regex:
(?<Name>(?:Name=)\w+)?\,?(?<Age>(?:Age=)\d+)?\,?(?<Height>(?:Height=)[\d.]+)?\,?(?<Occupation>(?:Occupation=)\w+)?\,?
Result:
Full match `Name=Jennifer,Age=29,Height=1.70,Occupation=Actress`
Group `Name` `Name=Jennifer`
Group `Age` `Age=29`
Group `Height` `Height=1.70`
Group `Occupation` `Occupation=Actress`
How to make keys not part of the group, but check if they exist?
Upvotes: 1
Views: 230
Reputation: 626794
Generally, it is a bad idea to use a regex that only consists of optional patterns (because you need to handle empty matches, the patterns only match in a predefined order, and it is not possible to make it work with positive lookaheads since all are optional). It will make more sense to just use Name=(\w+)
, Age=(\d+)
like regexes to extract all the necessary details.
If you want to follow your path, you may try fixing your pattern by putting the keys outside the capturing groups:
(?:Name=(?<Name>\w+))?,?(?:Age=(?<Age>\d+))?,?(?:Height=(?<Height>[\d.]+))?,?(?:Occupation=(?<Occupation>\w+))?,?
See the regex demo
Upvotes: 1