无法增加在正则表达式匹配的第 1 组中捕获的数字

Not able to increment numbers captured in Group 1 of a regex match

我需要将文本文件中的所有数字(不是单词的一部分)递增 1。我尝试使用模式 \b(\d+)\b 来捕获所有此类数字,但我无法在文件中递增(向它们加 1)它们。

输入

text1
    1 5 7
hello world 5. This is Samurai 10 not samurai10.
text2

预期输出

text1
    2 6 8
hello world 6. This is Samurai 11 not samurai10.
text2

我的尝试

const forReading = 1
set objFso = createObject("scripting.filesystemobject")
strFilePath = split(wscript.scriptFullName,wscript.scriptName)(0) & "haha.txt"
set objFile = objFso.openTextFile(strFilePath, forReading)
set objReg = new RegExp
With objReg
    .Global = True
    .ignoreCase = true
    .multiline = true
    .pattern = "\b(\d+)\b"
End With

    strTemp = objFile.readAll()
    strTemp = objReg.replace(strTemp,cint("")+1)      '<--Here, I am getting the "Type mismatch 'Cint'" error. I just wanted to increment the number which was captured in Group 1
    msgbox strTemp

set objFile = Nothing
set objFso = Nothing

如果我将行 strTemp = objReg.replace(strTemp,cint("")+1) 替换为 strTemp = objReg.replace(strTemp,"__"),我会得到以下输出,这意味着我能够获得需要递增的所需数字:

我只是无法增加它们。非常感谢任何帮助!!!

使用 cint(""),您试图将 </code> 字符串转换为 <code>int,而不是捕获的数字本身。

您可以使用以下解决方法:

Dim strTemp As String, val As String
Dim offset As Integer
Dim objReg As regExp

strTemp = "text1" & vbLf & "    1 5 7" & vbLf & "hello world 5. This is Samurai 10 not samurai10." & vbLf & "text2 "

Set objReg = New regExp
With objReg
    .Global = True
    .Pattern = "\b\d+\b"
End With

For Each m In objReg.Execute(strTemp) ' Get all the matches in the original string
    val = CStr(CInt(m.Value) + 1)  ' The incremented matched number value
    strTemp = Left(strTemp, m.FirstIndex + offset) _
        & val _
        & Mid(strTemp, m.FirstIndex + Len(m.Value) + offset + 1) ' Text before match, modified value, the rest
    offset = offset + Len(val) - Len(m.Value) ' Need this to calculate the right index of the next match since when incrementing, the strTemp length may differ from its original length and match indices will mismatch
Next m

针对 strTemp = "ab2cd99def999""\d+" 正则表达式使用相同的代码会产生预期的 ab3cd100def1000.

只需替换代码:

strTemp = objReg.replace(strTemp,cint("")+1)

set objMatches = objReg.execute(strTemp)
for each match in objMatches
    strTemp = left(strTemp, match.firstIndex) & replace(strTemp, match.value, cInt(match.value)+1, match.firstIndex+1, 1)
next
msgbox strTemp

这是我得到的输出:

检查 replace 函数的引用