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

时间:2019-02-25 11:56:37

标签: regex vbscript

我需要将文本文件中的所有数字(不是单词的一部分)加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")+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")+1)替换为strTemp = objReg.replace(strTemp,"_$1_"),则会得到以下输出,这意味着我能够获得需要增加的所需数字:

enter image description here

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

2 个答案:

答案 0 :(得分:3)

使用@BeforeClass final String xyz = System.getProperty("XYZ"); ,您尝试将cint("$1")字符串强制转换为$1,而不是捕获的数字本身。

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

int

enter image description here

针对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+"

答案 1 :(得分:1)

只需替换代码:

strTemp = objReg.replace(strTemp,cint("$1")+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

这是我得到的输出:

enter image description here

检查 replace 功能的参考