正则表达式组重排

问题描述

我认为我的方法本身在匹配组方面是错误的。可以做些聪明的事吗?

我的表情是:

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

以下是链接regexr

我的输入是:

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

预期输出为:

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

如您在屏幕快照中所见,replace表达式在第2和第5组的第一种情况下有效。

enter image description here

对于第二种情况,我必须使用第二组和第七组。

enter image description here

我想我已经在这里打结了。 除了小组以外,还有其他更好的方法吗?

并且我预先使用正则表达式解开xml。我必须处理我递​​给的卡片。

解决方法

我认为您只需要两个小组:

  1. Group1:记录类型
  2. Group2:记录的值

您可以尝试使用正则表达式。

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

详细信息:

  • (\w*):第1组-记录类型
  • (?:value="|utcdate="):非捕获组-匹配value =“或utcdate =”
  • (.*?):第2组-记录的值

我在https://regexr.com/5b9c9中验证了结果

enter image description here