正则表达式省略花括号

标签 regex vba vbscript

目前我在 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/

相关文章:

javascript - REGEX 在 MVC4 Razor/Javascript 中使用上标格式化小数

excel - 将 VBA 公式插入定义的范围

excel - 使用 selenium VBA 登录具有两个表单组的网站

asp.net - VBScript/IIS - 如何为特定网站自动设置 ASP.NET 版本

vbscript - 为什么 VBScript 的按位 And 在一种情况下失败?

javascript - 具有最小值和千位分隔符的数字的正则表达式

php - Python 正则表达式到 PHP?

javascript - 替换每次出现的 [b : "text"] to <b>text</b> where text can be anything

sql-server - VBA - SQL 查询字符串

vbscript - 在 vbs 中比较两个字符串时,Trim 函数不会删除字符串末尾的空格