vb.net - 替换确切的单词
问题描述
我想转换这个字符串:
"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”。
如何使替换更具体?
解决方案
您可以将其视为 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}
推荐阅读
- php - andWhere 条件学说 CreateQueryBuilder 的问题
- selenium - 启用 JavaScript 的 Selenium 不会跳过
- angular - Angular - NgRx - difference between .select(...) and .pipe(select...)
- javascript - Why do my onclick function only work once?
- postgresql - How to connect postgresql database server deployed on azure cloud to an app service on azure which uses prisma db?
- mysql - mysql - Set temporary variable to store more than 1 records?
- javascript - How can I upload images in node from a POST request
- prettier - Standalone prettier, html formatter isn't properly formatting JS
- javascript - 将对象推送到对象数组导致对整个数组的意外更改
- windows - run "Programs and Features" on another computer in domain