繁体   English   中英

如何从vb.net中的正则表达式匹配中获取字符串?

[英]How to get a string from a regex match in vb.net?

我有 :

Dim Text = "some text here ###MONTH-3### some text here ###MONTH-2### some text here"
Dim regex = New System.Text.RegularExpressions.Regex("###MONTH[+-][0-9]###")
For Each match In regex.Matches(Text)
    // What to write here ?
    // So, that ###MONTH-i### gets replaced with getmonth(i)
    // Therefore, final Text will be :
    // Text = "some text here" + getmonth(-3) + "some text here" + getmonth(-2) + "some text here"
Next match

我想我已正确解释了我的问题..

那么,你能帮忙吗?

我想这就是你想要的。

Dim text As String = "some text here ###MONTH-3### some text here ###MONTH-2### ..."
Dim regex = New System.Text.RegularExpressions.Regex("###MONTH[+-][0-9]###")

return regex.replace(text, AddressOf GetMonthFromMatch)

Function GetMonthFromMatch(ByVal m As Match) As String
    ' Get the matched string.
    Dim matchText As String = m.ToString()

    Dim offset As Int = Integer.Parse(matchText.Right(2))
    Return getmonth(offset)
End Function

这使用GetMonthFromMatch委托处理每个匹配,然后调用getmonth函数。 RegEx.Replace函数将使用委托替换每个匹配。

首先稍微修改你的正则表达式:

System.Text.RegularExpressions.Regex("###MONTH([+-][0-9])###")

如您所见,我只是在括号中加上数字和+/-。 这样我们以后可以检索它们。

所以现在你只需要访问这些代码所需的数据(例如-3):

match.Groups(1).Value

编辑:

甚至更简单的方法:)只需使用替换功能。

在您的示例中,它将如下所示:

Dim regex = New System.Text.RegularExpressions.Regex("###MONTH([+-][0-9])###")
regex.Replace(Text, "getmonth($1)")

1美元引用正则表达式中的第一个括号,因此实际上它将是月份而不是1美元。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM