【发布时间】:2018-06-21 14:37:47
【问题描述】:
我正在尝试用查询 wID=[[WID]] 替换 URL 查询模式 wID=xxx,其中 xxx 可以是数字、数字或空格(请注意,查询区分大小写)。我想知道我怎样才能做到这一点。目前,我正在使用正则表达式在 URL 中查找模式并使用 Regex.Replace() 替换它,如下所示:
private const string Pattern = @"wID=^[0-9A-Za-z ]+$";
private const string Replace = @"wID=[[WID]]";
/// <summary>
/// Extension method to evaluate the url token for wid
/// </summary>
/// <param name="rawUrl">Incoming URL</param>
/// <returns>Expected URL</returns>
public string GetUrl(string rawUrl)
{
if (string.IsNullOrWhiteSpace(rawUrl))
{
return string.Empty;
}
string result = Regex.Replace(rawUrl, Pattern, Replace);
return result;
}
但这并没有给我想要的输出,因为正则表达式模式不正确,我想。有更好的方法吗?
我的问题与实现正则表达式模式以查找和替换 URL 查询参数值有关,我发现 URI 构建器在这些情况下更有帮助并且可以使用,所以这是不同的问题。
【问题讨论】:
-
您不应该为此使用正则表达式,已经有内置库可以帮助您解析 URI。如果您包含示例 URL,我可以提供无正则表达式的答案
-
一个示例 URL 是“fod.infobase.com/PortalPlaylists.aspx?xtid=10112&wID=123” wID 的位置可以在 URL 中的任何位置
-
您需要对
[和]进行转义吗? -
我看到了 URL,我在问你是否希望得到的 url 有
[和]字符转义?