首页 > 解决方案 > 使用 RegEx 从字符串中提取数据行

问题描述

我有几个字符串,例如

(3)_(9)--(11).(FT-2)
(10)--(20).(10)/test--(99)

我正在尝试 Regex.Match(这里我不知道)来获得这样的列表: 第一个示例:

3
_
9
--
11
.
FT-1

第二个样本:

10
--
20
.
10
/test--
99

所以括号中有几个数字以及它们之间的任何文本。谁能帮我在 vb.net 中这样做?给定的字符串返回这个列表?

标签: regexvb.net

解决方案


一种选择是使用以下Split方法[String]

"(3)_(9)--(11).(FT-2)".Split('()')

另一种选择是匹配所有内容,不包括()

作为正则表达式,这会做[^()]+

分解

"[^()]" ' Match any single character NOT present in the list “()”
   "+"  ' Between one and unlimited times, as many times as possible, giving back as needed (greedy)

您可以使用以下代码块来提取所有匹配项

Try
    Dim RegexObj As New Regex("[^()]+", RegexOptions.IgnoreCase)
    Dim MatchResults As Match = RegexObj.Match(SubjectString)
    While MatchResults.Success
        ' matched text: MatchResults.Value
        ' match start: MatchResults.Index
        ' match length: MatchResults.Length
        MatchResults = MatchResults.NextMatch()
    End While
Catch ex As ArgumentException
    'Syntax error in the regular expression
End Try

推荐阅读