Regex 使用正则表达式提取插入数据
我有一个小sub,它从字符串中提取插入式数据(包括括号),并将其存储在字符串旁边的单元格中:Regex 使用正则表达式提取插入数据,regex,excel,vba,Regex,Excel,Vba,我有一个小sub,它从字符串中提取插入式数据(包括括号),并将其存储在字符串旁边的单元格中: Sub parens() Dim s As String, i As Long Dim c As Collection Set c = New Collection s = ActiveCell.Value ary = Split(s, ")") For i = LBound(ary) To UBound(ary) - 1 bry = S
Sub parens()
Dim s As String, i As Long
Dim c As Collection
Set c = New Collection
s = ActiveCell.Value
ary = Split(s, ")")
For i = LBound(ary) To UBound(ary) - 1
bry = Split(ary(i), "(")
c.Add "(" & bry(1) & ")"
Next i
For i = 1 To c.Count
ActiveCell.Offset(0, i).NumberFormat = "@"
ActiveCell.Offset(0, i).Value = c.Item(i)
Next i
End Sub
例如:
我现在尝试用一些正则表达式代码来替换它。我不是正则表达式专家。我想创建一个模式,该模式查找一个开括号,后跟零个或多个任意类型的字符,后跟一个右括号。
我想到了:
\((.+?)\)
我目前的新代码是:
Sub qwerty2()
Dim inpt As String, outpt As String
Dim MColl As MatchCollection, temp2 As String
Dim regex As RegExp, L As Long
inpt = ActiveCell.Value
MsgBox inpt
Set regex = New RegExp
regex.Pattern = "\((.+?)\)"
Set MColl = regex.Execute(inpt)
MsgBox MColl.Count
temp2 = MColl(0).Value
MsgBox temp2
End Sub
该代码至少有两个问题:
- 它将只获取字符串中的第一个匹配项。(Mcoll.Count始终为1)
- 它将无法识别括号之间的零个字符。(我认为+?至少需要一个字符)
*?
,而不是+?
。请注意,两者都是惰性的(尽可能少地匹配以找到有效匹配),但+
至少需要一个字符,而*
允许匹配零字符(空字符串)
因此,使用
Set regex = New RegExp
regex.Global = True
regex.Pattern = "\((.*?)\)"
至于正则表达式,您还可以使用
regex.Pattern = "\(([^()]*)\)"
其中,
[^()]
是一个否定字符类,匹配任何字符,但(
和)
,零次或多次(由于*
量词),匹配尽可能多的此类字符(*
是贪婪量词)。再次感谢。。。。。。。。。。。。。。。。。。。。。完美的谢谢你的解释!