如何用数组中包含的值替换字符串中未知数量的单词?

时间:2019-04-18 18:27:59

标签: string vb.net

给出一个字符串,我如何依次用数组中的内容替换以“#”开头的单词。

例如。

dim s as string = "select * from tb where p1 = #p1 and p2 = #p2"
dim param() as string = {"value1", "value2"}

我正在寻找:

dim result = "select * from tb where p1 = value1 and p2 = value2"

我正在尝试类似的方法,但是它不起作用

            Dim paramIndex As Integer = 0
            Dim m() As String
                m = Query.Split(" ")
            For Each ma In m
                If ma.IndexOf("#") >= 0 Then
                    ma = "'" & param(paramIndex) & "'"
                    paramIndex += 1
                End If
            Next
            Query = String.Join(" ", m)

我发现了一些类似的问题,但对于vb.net来说都没有

1 个答案:

答案 0 :(得分:-1)

此函数使用正则表达式查找以#开头的所有单词,然后循环遍历并将其替换为数组值:

Private Function replaceSubStrings(input As String, params As String()) As String
    Dim pattern = New Text.RegularExpressions.Regex($"#\w+")
    Dim matches = pattern.Matches(input)
    Dim output = input
    For i = 0 To matches.Count - 1
        output = output.Replace(matches(i).Value, params(i))
    Next
    Return output
End Function

这是它的用法:

Dim input = "select * from tb where p1 = #p1 and p2 = #p2"
Dim param = {"value1", "value2"}
Dim result = replaceSubStrings(input, param)

结果:

  

从tb中选择*,其中p1 = value1和p2 = value2