【问题标题】:Replace string between specific characters [duplicate]替换特定字符之间的字符串[重复]
【发布时间】:2017-10-06 20:01:23
【问题描述】:

我想知道如何使用正则表达式替换两个字符之间的字符串。

var oldString  = "http://localhost:61310/StringtoConvert?Id=1"

预期结果 = "http://localhost:61310/ConvertedString?Id=1"

【问题讨论】:

  • 你有什么尝试吗?查看有关如何使用正则表达式的任何文档?
  • 可能this帮助
  • 感谢大家的帮助。我已经实现了私有静态字符串 ReplacePath(string url, string newPath) { Uri uri = new Uri(url);返回 $"{uri.GetLeftPart(UriPartial.Authority)}/{path}{uri.Query}"; } 并且它有效
  • @AshishParajuli 使用 Eser 的解决方案,它比我的要好。也将他们的答案标记为正确的

标签: c# regex


【解决方案1】:

不需要正则表达式或字符串操作,使用 UriBuilder 类。

var oldString = "http://localhost:61310/StringtoConvert?Id=1";
var newuri = new UriBuilder(new Uri(oldString));
newuri.Path = "ConvertedString";
var result = newuri.ToString();

【讨论】:

  • 我什至不知道这个类的存在哈哈,这个答案胜过我的!
  • 如果您想将它包含在您的答案中,我对您的代码做了一个分支,请参阅here
【解决方案2】:

您可以使用Regex.Replace(string, string, string)。因此,如果要替换 /? 之间的子字符串,可以使用

string result = Regex.Replace(oldString, "(?<=\/)[^\?]*(?=\?)", "ConvertedString");

?&lt;= 是后视,\/ 转义斜杠字符,[^\?]* 匹配任何不是 ?任意次数,?= 是一个前瞻,\? 转义问号字符。

【讨论】:

  • string result = Regex.Replace(oldString, "(http\:\/\/localhost\:61310\/)(\w+)(\?Id\=1)", "$1ConvertedString$3");
【解决方案3】:

您可以使用 System.Uri 类代替正则表达式,然后连接或插入您的新值:

private static string ReplacePath(string url, string newPath)
{
    Uri uri = new Uri(url);     
    return $"{uri.GetLeftPart(UriPartial.Authority)}/{newPath}{uri.Query}";
}

用你的url调用这个方法,新的路径(即“ConvertedString”)将产生输出:"http://localhost:61310/ConvertedString?Id=1"

小提琴here.

编辑

@Eser 的回答比我的要好得多。不知道这个类的存在。将他们的答案标记为不是我的

【讨论】:

  • 谢谢 maccettura。我喜欢你的接近。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
相关资源
最近更新 更多