我有一个句子“lorem ipsum dolor 标记词 blah blah blah”
我只需要“标记词”之后的词(但不包括)。 “标记词”是句子中唯一保持不变的词。
我设法找到(?<=\bmarker words\s)(\w+)
这不仅在 vba 中不起作用,而且它还只返回标记词之后的一个词,例如:blah
但我不确定如何将其扩展到字符串的其余部分(如果我要在 Excel 之外处理它)。我的研究表明,vba 根本不支持lookbehind,所以我陷入困境。
最佳答案
VBA VBScript 正则表达式不支持lookbehind 构造。您只能依靠捕获:
\bmarker words\s+(.*)
请参阅regex demo
\bmarker Words\s+
子模式匹配整个单词marker Words
,后跟 1 个或多个空格和 (.*)
子模式匹配除换行符之外的零个或多个字符,并将其放入捕获组(内存缓冲区)中,可以使用特定于语言的方法进一步检索该值。
VBA代码:
Sub CaptureSubstring()
Dim str As String
Dim objMatches As Object
str = "lorem ipsum dolor marker words blah blah blah"
Set objRegExp = CreateObject("VBScript.RegExp") ' Declare the RegExp object
objRegExp.Pattern = "\bmarker words\s+(.*)" ' Set pattern
Set objMatches = objRegExp.Execute(str) ' Execute the regex match
If objMatches.Count <> 0 Then ' Check the result
Debug.Print objMatches.Item(0).SubMatches.Item(0) ' Print Match 1, Submatch 1
' > blah blah blah
End If
End Sub
关于regex - VBA正则表达式单词后的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35855040/