开发者

c# and Regex: How do I make a match?

Aloha,

I need to match page.aspx?cmd=Show&id= but not match http://random address/page.aspx?cmd=Show&id=

Right now I'm just doing a simple resting replace with strContent.Replace("page.aspx?cmd=Show&id=", "page.aspx/Show/"); but to avoid the above i think I need to move to regular expressions.

Edit: Sorry i was a little short on details The current replace works because I was not taking into account that the address being modified should only be relative addresses, not absolute. I need to catch all relative addresses that match page.aspx?cmd=Show&id= and convert that string into page.aspx/Show开发者_运维问答/.

The .StartsWith and ^ wont work because I an looking in a string that is a full html page. So I need to be able to convert:

<p>Hello, please click <a href="page.aspx?cmd=Show&id=10">here</a>.</p>

into

<p>Hello, please click <a href="page/Show/10">here</a>.</p>

but not convert

<p>Hello, please click <a href="http://some address/page.aspx?cmd=Show&id=10">here</a>.</p>

I used an A tag for my example but I need to convert IMG tags as well.

Thanks!


I would suggest using ParseQueryString rather than a regular expression because this will work even if the parameters are in a different order.

Otherwise you can use string.StartsWith to test if there is a match.

If you want to use a regular expression you need to use ^ and also escape all the special characters in your string:

Regex regex = new Regex(@"^page\.aspx\?cmd=Show&id=");

If you don't want to escape the characters yourself you can get Regex.Escape to do it for you:

string urlToMatch = "page.aspx?cmd=Show&id=";
Regex regex = new Regex("^" + Regex.Escape(urlToMatch));


You can just use a ^ to look for start of line.
... Or you can be cool and use a negative lookbehind (?<!http://.*?/). ;)

See http://www.geekzilla.co.uk/View6BD88331-350D-429F-AB49-D18E90E0E705.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜