目前我在 VBA 中的正则表达式捕获大括号中的所有内容(包括大括号):
模式 = "\{\w*\}"
是否可以在正则表达式级别省略大括号?
所以{计算机1}{计算机2}
成为 Computer1 计算机2
完整代码如下:
Dim RegEx As Object
Set RegEx = CreateObject("VBScript.RegExp")
With RegEx
.Global = True
.IgnoreCase = True
.MultiLine = True
.Pattern = "\{\w*\}"
End With
最佳答案
在支持后向查找的正则表达式风格中,您可以执行以下操作:
(?<={)\w*(?=})
这只匹配大括号的内容。请注意,为了避免返回空字符串,您可以将 *
更改为 +
但是VBscript不支持lookbehind。
相反,您可以使用括号将内容捕获到组 1:
{(\w+)}
这是查看它的代码,由 RegexBuddy 生成(无法评论,因为我不使用 VBScript):
Dim myRegexp, contentOfBraces, myMatches, myMatch As Match
Dim myRegexp As RegExp
Set myRegexp = New RegExp
myRegexp.Pattern = "{(\w+)}"
Set myMatches = myRegexp.Execute(SubjectString)
If myMatches.Count >= 1 Then
Set myMatch = myMatches(0)
If myMatch.SubMatches.Count >= 1 Then
contentOfBraces = myMatch.SubMatches(1-1)
Else
contentOfBraces = ""
End If
Else
contentOfBraces = ""
End If
关于正则表达式省略花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152317/