gpt4 book ai didi

c# - regex.replace 查询字符串参数

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:32 24 4
gpt4 key购买 nike

我不知道这是否可能,我有以下正则表达式 (?<=[\?|\&])(?[^\?=\&#]+)=?(?[ ^\?=\&#]*)& 将 URL 拆分为键/值对。我想在替换函数中使用它来构建一些标记:

string sTest = "test.aspx?width=100&height=200&";
ltTest.Text = Regex.Replace(sTest, @"(?<=[\?|\&])(?<key>[^\?=\&\#]+)=?(?<value>[^\?=\&\#]*)&",
"< div style='width:$2px; height:$2px; border:solid 1px red;'>asdf</div>");

这是生成:

test.aspx?<div style='width:100px; height:100px; border:solid 1px red;'>asdf</div><div style='width:200px; height:200px; border:solid 1px red;'>asdf</div>

有什么想法吗?

提前致谢!

最佳答案

首先,.net 有更好的方法来处理您的问题。考虑 HttpUtility.ParseQueryString :

string urlParameters = "width=100&height=200";
NameValueCollection parameters = HttpUtility.ParseQueryString(urlParameters);
s = String.Format("<div style='width:{0}px; height:{1}px;'>asdf</div>",
parameters["width"], parameters["height"]);

这会为您处理转义,因此这是一个更好的选择。


接下来,对于问题,您的代码失败是因为您使用错误。你正在寻找成对的 key=value , 并<div width={value} height={value}> 替换每一对 .所以你最终会得到许多 DIV 作为值。
例如,您应该进行更外科手术式的匹配(添加一些检查):

string width = Regex.Match(s, @"width=(\d+)").Groups[1].Value;
string height = Regex.Match(s, @"height=(\d+)").Groups[1].Value;
s = String.Format("<div style='width:{0}px; height:{1}px;'>asdf</div>",
width, height);

关于c# - regex.replace 查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2269479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com