我试图从一个string中的括号内提取文本。 例:
"John D Wilson(some text)"
我只想从string中提取some text
。
这是我到目前为止的代码:
temp = workingValue rawname=split(temp) dim value Set myRegExp = New RegExp myRegExp.IgnoreCase = True myRegExp.Global = True myRegExp.Pattern = "/\([az]+\)/" msgbox temp if myRegExp.Test(temp)then value = myRegExp.Replace(temp,"") msgbox value else msgbox "no match" end if
通过使用组,您可以将括号之间的文本作为子匹配提取。 尽管你的模式不起作用,因为你的示例文本包含空格,但是你的模式不包含空格。 尝试这样的事情:
myRegExp.Pattern = "/\((.*?)\)/" For Each m In myRegExp.Execute(temp) value = m.SubMatches(0) Next If IsEmpty(value) Then MsgBox "no match" Else MsgBox value End If
正则表达式细分:
\(...\)
匹配括号。 .*?
是除了换行符之外的任何字符的非贪婪匹配。 (...)
是一个捕获组,因此非贪婪匹配可以作为子匹配来访问。 您的正则表达式在some text
中与空格不匹配
另外,如果你需要将捕获组放在文本中
只想分离/提取文本。
其中之一可能工作
\(([^()]+)\)
\(([az]+(?:\s+[az]+)*)\)/
\(([a-zA-Z\s]+)\)