Reputation: 45
I am new to regex and I need your help. I need to parse the following text:
2DB337649|required-match|groupName1=value1^groupName2=value2^junk1=junkval^junk2=junkval^groupName3=value3^junk3=junkval^groupName4=value4^`
I need to get the values out of it while ignoring the junk. I have used the following regex:
(?=.*required-match).+groupName1=(?<group1>.*?)\^groupName2=(?<group2>[^^]+).+groupName3=(?<group3>[^^]+).+groupName4=(?<group4>.*?)\^
I works fine but the problem is that sometimes value groupName3 is missing and I get no matches.
Is there a way to get the groupName3 if it is found and if not just go further to groupName4?
Thank you.
Upvotes: 0
Views: 41
Reputation: 163632
The part with groupName3
can be in an optional non capturing group and you could make the .+
non greedy using .*?
(?:.+?groupName3=(?<group3>[^^]+))?
The pattern might look like
(?=.*required-match).+?groupName1=(?<group1>.*?)\^groupName2=(?<group2>[^^]+)(?:.+?groupName3=(?<group3>[^^]+))?.+?groupName4=(?<group4>.*?)\^
Upvotes: 2