使用正则表达式提取指定符号之间的所有子字符串

时间:2018-08-11 14:18:40

标签: vba

Excel 2007

我想从一个短语中提取符号“ /”之间的子字符串。

Private Function get_all_matches(phrase)
    Dim regEx As Object
    Dim result As Variant

    Set regEx = CreateObject("vbscript.regexp")

    With regEx
        .IgnoreCase = True
        .Pattern = "/.*/"
        .Global = True
    End With

    Set result = regEx.Execute(phrase)
    Set get_all_matches = result
End Function

然后我使用函数:

phrase = "where is /my/ ups /hiding/"
Set keys = get_all_matches(phrase)

结果是keys(0).Value:“ / my / ups / hide/"。

换句话说,外斜线之间的所有内容均被提取。 但是预期结果是:

keys(0).Value: "/my/"
keys(1).Value: "/hiding/"

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

您应该使用\/(.*?)\/模式

模式说明:

  

/ 匹配字符/按字面意义(区分大小写)第一次捕获

     

(。?) ?匹配任何字符(行终止符除外)

     

*?量词-匹配零次和无限制次数,尽可能少的次数,根据需要扩展(惰性)/匹配字符/

在这里测试-> https://regex101.com/r/wdNY18/1

相关问题