2

我有这个网址模式

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

让我们这么说locality并且userLocation没有价值

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  
4

2 回答 2

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"
于 2013-08-22T14:09:06.597 回答
2

@"[\w]+=\&" 应该可以为您提供所需的内容,但是如果相应的值为空,则简单地不将参数添加到 url 字符串中不是更容易吗?

于 2013-08-22T14:09:26.607 回答