如何删除Regex中的特定url参数?

时间:2013-08-22 14:04:25

标签: 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  

2 个答案:

答案 0 :(得分:4)

为什么你特别想要使用正则表达式? 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"

答案 1 :(得分:2)

@ “[\ W] + = \&安培;”应该得到你想要的东西,但如果相应的值是空的,那么简单地不将参数添加到url字符串会不会更容易?