当我在文章中间插入新参考文献时,我在替换 MS word 中的某些序列号时遇到问题,例如 [30] [31] [32]... 到 [31] [32] [33]... . 我还没有在 GUI 中找到解决方法,所以我尝试使用 VBA 来进行替换。我在堆栈溢出中发现了类似的问题:
但是,这种方式有点不方便,因为它必须在其他地方生成一些替换数组。我可以用正则表达式和 MS Word VBA 中的一些函数进行替换,如下面的代码吗?
Sub replaceWithregExp()
Dim regExp As Object
Dim regx, S$, Strnew$
Set regExp = CreateObject("vbscript.regexp")
With regExp
.Pattern = "\[([0-9]{2})\]"
.Global = True
End With
'How to do some calculations with $1?
Selection.Text = regExp.Replace(Selection.Text, "[$1]")
End Sub
但我不知道如何用 regExp 中的 $1 进行一些计算?我尝试使用“[$1+1]”,但它返回 [31+1] [32+1] [33+1]。任何人都可以帮忙吗?谢谢!
不可能将回调函数传递给RegExp.Replace
,因此您只有唯一的选择:RegExp.execute
在循环中使用和处理匹配项。
这是您案例的示例代码(我采用了快捷方式,因为您只有在已知分隔符中修改的值,[
以及]
.)
Sub replaceWithregExp()
Dim regExp As Object
Dim regx, S$, Strnew$
Set regExp = CreateObject("vbscript.regexp")
With regExp
.Pattern = "\[([0-9]{2})]"
.Global = True
End With
'How to do some calculations with $1?
' Removing regExp.Replace(Selection.Text, "[$1]")
For Each m In regExp.Execute(Selection.Text)
Selection.Text = Left(Selection.Text, m.FirstIndex+1) _
& Replace(m.Value, m.Value, CStr(CInt(m.Submatches(0)) + 10)) _
& Mid(Selection.Text, m.FirstIndex + Len(m.Value))
Next m
End Sub
这里,
Selection.Text = Left(Selection.Text, m.FirstIndex+1)
- 获取之前的内容& Replace(m.Value, m.Value, CStr(CInt(m.Submatches(0)) + 10))
- 添加10
到捕获的号码& Mid(Selection.Text, m.FirstIndex + Len(m.Value))
- 追加捕获后的内容本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句