【问题标题】:How to get a string from a regex match in vb.net?如何从 vb.net 中的正则表达式匹配中获取字符串?
【发布时间】:2011-08-01 12:58:29
【问题描述】:

我有:

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

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

那么,你能帮忙吗?

【问题讨论】:

  • 是的,你真的应该开始使用 Option Explicit ...
  • 他可能正在使用Option Infer。编写编译器可以为您解决的代码毫无意义。
  • 没错,我想这对于文字和非常明显的表达是可以接受的。
  • 为什么建议您使用 Option Explicit ? > 这对这里有什么帮助?

标签: .net regex vb.net


【解决方案1】:

这就是你想要的,我想。

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 函数将使用委托替换每个匹配项。

【讨论】:

    【解决方案2】:

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

    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 将是它实际的月份。

    【讨论】:

    • 这将简单地将文字文本“getmonth(-3)”插入到输入字符串中。他想运行getmonth 函数并插入结果
    • Ya.. Justin 是对的.. 我想运行函数getmonth(-3) 并替换值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多