使用RegExp将单个斜杠上的字符串拆分 [英] Split string on single forward slashes with RegExp

查看:549
本文介绍了使用RegExp将单个斜杠上的字符串拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:哇,感谢这么多建议,但是我想要一个专门用于将来,更复杂的使用的regexp解决方案。

edit: wow, thanks for so many suggestions, but I wanted to have a regexp solution specifically for future, more complex use.

我需要支持分割文本VBA Excel中的字符串。我环顾四周,但解决方案是用于其他语言,或者我无法使其在VBA中工作。

I need support with splitting text string in VBA Excel. I looked around but solutions are either for other languages or I can't make it work in VBA.

我只想用单斜杠分割单词:

I want to split words by single slashes only:

text1/text2- split
text1//text2- no split
text1/text2//text3 - split after text1

我尝试使用regexp.split函数,但不要以为它在VBA中有效。当谈到模式时,我正在考虑如下:

I tried using regexp.split function, but don't think it works in VBA. When it comes to pattern I was thinking something like below:

(?i)(?:(?<!\/)\/(?!\/))

但执行搜索时我也会收到错误在我的宏中,它适用于以下网站: https://www.myregextester.com/index.php #sourcetab

but I also get error when executing search in my macro while it works on sites like: https://www.myregextester.com/index.php#sourcetab

推荐答案

您可以使用RegExp匹配方法,而不是拆分方法。您需要匹配 / 或双重 // 之外的任何字符,以获取所需的值。

You can use a RegExp match approach rather than split one. You need to match any character other than / or double // to grab the values you need.

这是正则表达式的包装(即交替)版本:

Here is a "wrapped" (i.e. with alternation) version of the regex:

(?:[^/]|//)+

这是一个演示

这里是一个更高效,但不太可读:

And here is a more efficient, but less readable:

[^/]+(?://[^/]*)*

请参阅另一个演示

这是一个有效的VBA代码:

Here is a working VBA code:

Sub GetMatches(ByRef str As String, ByRef coll As collection)

Dim rExp As Object, rMatch As Object

Set rExp = CreateObject("vbscript.regexp")
With rExp
    .Global = True
    .pattern = "(?:[^/]|//)+"
End With

Set rMatch = rExp.Execute(str)
If rMatch.Count > 0 Then
    For Each r_item In rMatch
        coll.Add r_item.Value
        Debug.Print r_item.Value
    Next r_item
End If
Debug.Print ""
End Sub

调用子项如下:

Dim matches As New collection
Set matches = New collection
GetMatches str:="text1/text2", coll:=matches

以下是上述3个字符串的结果:

Here are the results for the 3 strings above:

1. text1/text2
 text1
 text2

2. text1/text2//text3
 text1
 text2//text3

3. text1//text2
 text1//text2

这篇关于使用RegExp将单个斜杠上的字符串拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆