我将如何应用此正则表达式规则

时间:2013-10-09 18:38:59

标签: regex vb.net replace integer

在Visual Basic .NET(2010)中,我有一个包含Visual Basic代码的字符串类型。我正在尝试使用“正则表达式”

用CInt(整数)替换所有整数

所以来自:

Dim I As Integer = 0

要:

Dim I As Integer = CInt(0)

这是我打算使用的正则表达式:http://regex101.com/r/rZ4sJ8

/\b(\d+)\b/CInt(\1)

我只是不知道如何应用它。我尝试了Regex.Replace()和Regex.Matches等,似乎没有什么可以做到的。我要么得到一个空白的结果,要么得到一个与输入无关的结果

2 个答案:

答案 0 :(得分:2)

在.NET中,您需要将搜索模式与替换模式分开,如下所示:

Dim input As String = "Dim I As Integer = 0"
Dim pattern As String = "\b(\d+)\b"
Dim replacement As String = "CInt($1)"
Dim output As String = Regex.Replace(input, pattern, replacement)

答案 1 :(得分:0)

这就是你需要的东西:

    Dim value As String = "Dim I As Integer = 13"
    Dim pattern As String = "\b(\d+)\b"
    Dim matches As MatchCollection = Regex.Matches(value, pattern)

    ' Loop over matches.
    For Each m As Match In matches
        ' Loop over captures.
        For Each c As Capture In m.Captures
            ' Replace original string
            value = value.Substring(0, c.Index) + "CInt(" + c.Value.ToString + ")"
        Next
    Next

虽然我会问你为什么需要首先进行替换!