1

在 Visual Basic .NET (2010) 中,我有这个字符串类型,它还包含一个 Visual Basic 代码。我正在尝试使用“正则表达式”将所有整数替换为 CInt(Integer)

所以从:

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 等,但似乎没有任何效果。我要么得到一个空白结果,要么得到一个与输入类似的结果

4

2 回答 2

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)
于 2013-10-09T18:52:01.123 回答
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

尽管我会质疑为什么您首先需要进行替换!

于 2013-10-09T18:43:15.323 回答