首页 > 解决方案 > Notepad++ RegEx 查找/替换指定的组和反向引用

问题描述

我在让我的 RegEx 查找/替换在 NPP 中工作数小时时遇到了一些麻烦。这是我正在处理的文件中的一些代码: https ://regex101.com/r/kQdy4L/6/ 我的目标是用他们的 id 替换所有“0>.|.|...”姓名

测试字符串

<movingPart index="0>8|1|3" referencePoint="0>8|1|0|4" referenceFrame="0>" scaleZ="true"/>
bla
bla
<i3dMapping id="KroneComprimaV180XC" node="0>" />
<i3dMapping id="novoGripPart2_fixPoint" node="0>8|1|0|4" />
<i3dMapping id="novoGrip_part2" node="0>8|1|3" />

替代

<movingPart index="novoGrip_part2" referencePoint="novoGripPart2_fixPoint" referenceFrame="KroneComprimaV180XC" scaleZ="true"/>
bla
bla
<i3dMapping id="KroneComprimaV180XC" node="0>" />
<i3dMapping id="novoGripPart2_fixPoint" node="0>8|1|0|4" />
<i3dMapping id="novoGrip_part2" node="0>8|1|3" />

经过一些 tial´n´error 我得到了这个 RegEx

(".[>].*?")|<i3dMapping id=(?P<name>".*?") node=(".[>].*?")
(".[>].*?")|<i3dMapping id=(?P<name>".*?") node=(".[>].*?")\=1

哪个确实找到了节点+ ID,或者只找到了我需要替换的节点,但是我不知道如何替换所有“0>。|。|。” 带有 id 名称

感谢您帮助我,这是我第一次遇到 RegEx,所以这对我来说非常困惑。干杯弗雷德

标签: regexreplacefindbackreference

解决方案


您可以使用此正则表达式为您进行替换:

(?<=(index|Point|Frame)=")([^"]+)(?=".*?id="([^"]+)" node="\2")

它对index=", Point="or之一使用正向回溯Frame="(请注意,我们必须切断,reference因为回溯必须是固定长度),然后是一些非"字符(该值在第 2 组中捕获),然后是正向预读对于一个看起来像引用之前捕获的值id="someidvalue" node="\2"的字符串。\2该值someidvalue在组 3 中捕获。

然后,您可以替换为$3. 请注意,您需要使用Replace All,由于某种原因 Notepad++ 不喜欢逐个匹配地替换它。

这是regex101.com上的正则表达式演示


推荐阅读