NotAgain
NotAgain

Reputation: 1977

Regex group rearrangement

I think my approach itself is wrong in terms of matching groups. Is it possible to do something clever?

My expression is:

<Record><((\w*)\s+((value="(.*?)")|(utcdate="(.*?)")).*?)></Record>

Here is the link: regexr

My input is:

<StepVal Name="Something"><Record><Time value="2.001" unit="s" /></Record></StepVal>
<StepVal Name="Something"><Record><Date utcdate="07/08/2015 04:40:14" timezone="UTC" /></Record></StepVal>

And expected output is:

<StepVal Name="Something"><Record type="Time" value="2.001"/></StepVal>
<StepVal Name="Something"><Record type="Date" value="07/08/2015 04:40:14"/></StepVal>

As you can see in the screenshot, the replace expression works in first case with 2nd and 5th group. enter image description here

And for second case I have to use 2nd and 7th group. enter image description here

I think I have tied myself in a knot here. Is there a better approach other than groups?

And I apolgise in advance for using regex to untie an xml. I have to deal with the cards I have been handed.

Upvotes: 0

Views: 50

Answers (1)

I think you only need two group:

  1. Group1: type of record
  2. Group2: value of record

You could try following regex.

<Record><(\w*)\s+(?:value="|utcdate=")(.*?)".*?><\/Record>

Details:

  • (\w*): Group1 - type of record
  • (?:value="|utcdate="): Non-capturing group - matches value=" or utcdate="
  • (.*?): Group2 - value of record

I verified the result in https://regexr.com/5b9c9

enter image description here

Upvotes: 1

Related Questions