【问题标题】:Advanced Visual Studio RegEx Replace高级 Visual Studio 正则表达式替换
【发布时间】:2011-12-21 09:03:52
【问题描述】:

我有多个带有 id 的部分。

<section id="01"></section>
<section id="02"></section>
<section id="03"></section>

我想做的是将所有这些 id 匹配并替换为自身 + 1,即 1 变为 2,2 变为 3,等等。

我已经做到了:

find:
id="{[0-9][0-9]}"
--
replace:
\0

【问题讨论】:

  • 呃 - 我不寒而栗地将 Visual Studio 搜索语法称为实际的正则表达式(即使它技术上是)...... blech!
  • 哦,是的——这绝对不能通过正常的正则表达式实现(包括... ,非常有限的情况......有点......

标签: xml regex visual-studio replace


【解决方案1】:

不要使用正则表达式。

使用 XmlDocument 加载它并使用 XPath。比如:

Dim tDoc as XmlDocument = New XmlDocument(xmlfilename)
For Each tNode As XmlNode In tDoc.SelectNodes("//sections/section")
  tNode.Attributes("id").Value = String.Format("{0:D2}", Int16.Parse(tNode.Attributes("id").Value) + 1)
Next

tDoc.Save(path)

【讨论】:

  • 是的,我不认为正则表达式(至少在 VS 的搜索和替换中)有能力对结果进行数学运算......只有简单的替换。
  • @danyim:你可以对正则表达式匹配做一些混蛋循环,从最后一个匹配开始,然后继续前进。但那会很丑。
【解决方案2】:

只需添加最后一个并删除第一个条目。

或者您可以一次匹配两个条目并使用反向引用,如果它们不是连续 ID,而只是随机数。

【讨论】:

  • 我无法让它工作......最后我只使用了小数。例如&lt;section id="2"&gt;&lt;/section&gt; &lt;section id="2.1"&gt;&lt;/section&gt; &lt;section id="3"&gt;&lt;/section&gt;
猜你喜欢
  • 1970-01-01
  • 2011-03-09
  • 2020-05-08
  • 2011-09-15
  • 1970-01-01
  • 2011-04-20
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
相关资源
最近更新 更多