c# - 如何删除正则表达式中的特定 url 参数?

标签 c# regex

我有这个网址模式

http://dev.virtualearth.net/REST/v1/Locations?
addressLine={0}&
adminDistrict={1}&
locality={2}&
countryRegion={3}&
postalCode={4}&
userLocation={5}&
inclnb=1&
key={6}  

假设 localityuserLocation 没有值

http://dev.virtualearth.net/REST/v1/Locations?
addressLine=Main&
adminDistrict=WA&
locality=&
countryRegion=US&
postalCode=98001&
userLocation=&
inclnb=1&
key=BingKey  

然后我想删除所有等于“&”的参数
例如:“locality=&”和“userLocation=&

应该是这样的:

http://dev.virtualearth.net/REST/v1/Locations?
addressLine=Main&
adminDistrict=WA&
countryRegion=US&
postalCode=98001&
inclnb=1&
key=BingKey  

最终输出:

http://dev.virtualearth.net/REST/v1/Locations?addressLine=Main&adminDistrict=WA&countryRegion=US&postalCode=98001&inclnb=1&key=BingKey  

最佳答案

为什么你特别想使用正则表达式? C# 中有一些专门用于构建和处理 URI 的类。我建议你看看HttpUtility.ParseQueryString()Uri.TryCreate .

然后,您将解析查询字符串,循环遍历只有键而没有值的变量,并在没有它们的情况下重建一个新的 uri。它比正则表达式更容易阅读和维护。

<小时/>

编辑:我很快决定看看如何做到这一点:

string originalUri = "http://www.example.org/etc?query=string&query2=&query3=";

// Create the URI builder object which will give us access to the query string.
var uri = new UriBuilder(originalUri);

// Parse the querystring into parts
var query = System.Web.HttpUtility.ParseQueryString(uri.Query);

// Loop through the parts to select only the ones where the value is not null or empty  
var resultQuery = query.AllKeys
                       .Where(k => !string.IsNullOrEmpty(query[k]))
                       .Select(k => string.Format("{0}={1}", k, query[k]));

// Set the querystring part to the parsed version with blank values removed
uri.Query = string.Join("&",resultQuery);

// Done, uri now contains "http://www.example.org/etc?query=string"

关于c# - 如何删除正则表达式中的特定 url 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382747/

相关文章:

c# - DDD : How to handle one entity stored in multiple storage systems?

c# - 如何在单个 Google 搜索结果页面中获得 50 个结果?

regex - 使用正则表达式匹配 vim 中的括号时的奇怪行为

r - str_extract 仅捕获重复出现的关键字的一个实例

python re 模块 - 用于提取文本片段的正则表达式

c# - 基于类型变量实例化不同存储库的策略模式

c# - 带有更新面板的 jquery

c# - 从 IL 创建方法的副本

javascript - 如何每三个字符插入一个空格到句点字符?

c - 正则表达式 Linux 和 CSV 文件