使用正则表达式解析参数值含未编码&符号的查询字符串
未编码&查询字符串解析方案
直接使用支持正向零宽断言的正则即可完成正确拆分,核心逻辑是识别参数分隔边界为**「&符号+合法参数名+等号」**,而非单独的&符号,避免把参数值内部的&误判成分隔符。
可用正则表达式:
([^&=]+)=(.*?)(?=&[^&=]+=|$)
正则逻辑说明
- 第一个捕获组
([^&=]+):匹配参数名,匹配所有不包含&、=的连续字符,覆盖常规查询参数名格式 =:匹配参数名与参数值之间的固定分隔符- 第二个捕获组
(.*?):以非贪婪模式匹配参数值内容 - 正向断言
(?=&[^&=]+=|$):定义参数值的匹配终止边界:要么遇到后续紧跟「合法参数名+等号」的&分隔符,要么到达字符串末尾,不会截断参数值内部的&字符。
C# 实现示例
using System; using System.Collections.Generic; using System.Text.RegularExpressions; public static class QueryStringParser { public static Dictionary<string, string> ParseInvalidQuery(string rawQuery) { var result = new Dictionary<string, string>(); const string pattern = @"([^&=]+)=(.*?)(?=&[^&=]+=|$)"; var matches = Regex.Matches(rawQuery, pattern); foreach (Match match in matches) { result[match.Groups[1].Value] = match.Groups[2].Value; } return result; } // 测试用例 public static void Main() { string testInput = "param1=test¶m2=cpd&cpd¶m3=abc"; var parsed = ParseInvalidQuery(testInput); foreach (var item in parsed) { Console.WriteLine($"{item.Key} = {item.Value}"); } } }
运行上述测试代码,输出结果完全符合预期:
param1 = test param2 = cpd&cpd param3 = abc
注意:该方案适用前提为参数名本身不包含
&、=特殊字符,和当前第三方返回数据场景完全适配。
内容的提问来源于stack exchange,提问作者Alex Kvitchastyi
相关产品推荐
相关产品推荐

