首页 > 解决方案 > 替换确切的单词

问题描述

我想转换这个字符串:

"http://www.example.com/sms.aspx?user=joey&pass=joey123&mbno=9792234567&msg=Test"

对此:

"http://www.example.com/sms.aspx?user={0}&pass={1}&mbno={2}&msg={3}"

但我得到这样的输出:

"http://www.example.com/sms.aspx?user={0}&pass={0}123&mbno={2}&msg={3}".

我使用以下代码行进行替换:

Dim SMSUrlStr As String="http://www.example.com/sms.aspxuser=joey&pass=joey123&mbno=9792234567&msg=Test"

例如 Regex.Replace(SMSUrlStr, joey, {0})

但它也在替换“joey123”中的“joey”。

如何使替换更具体?

标签: vb.net

解决方案


您可以将其视为 URI,而不是将输入视为字符串。框架中有一些方法可以处理 URI,我们可以根据这些方法将其重建为您需要的形式:

Imports System.Collections.Specialized
Imports System.Text
Imports System.Web

Module Module1

    Sub Main()
        Dim s = "http://www.example.com/sms.aspx?user=joey&pass=joey123&mbno=9792234567&msg=Test"
        Dim u = New Uri(s)
        Dim q = HttpUtility.ParseQueryString(u.Query)

        Dim newQ = q.AllKeys.Select(Function(p, i) p & "={" & i & "}")

        Dim newS = u.GetLeftPart(UriPartial.Path) & "?" & String.Join("&", newQ)

        Console.WriteLine(newS)
        Console.ReadLine()

    End Sub

End Module

输出:

http://www.example.com/sms.aspx?user={0}&pass={1}&mbno={2}&msg={3}

推荐阅读