正则表达式将url参数字符串转换为路径

时间:2009-12-09 23:20:03

标签: c# .net regex

需要正则表达式更改为url

abc.aspx?str=blue+lagoon&id=1234 

/blog/blue-lagoon/

2 个答案:

答案 0 :(得分:5)

in perl:

my $work_url = $original_url; 
$work_url =~ s/\+/-/g;
$url = '/blog/' . do { $work_url =~ m/\bstr=([\w\-]+)\b/; $1} . '/';

适用于给出的示例。

灵感来自Ragepotato:

$new_url = '/blog/'
    . sub { local $_ = shift; tr/+/-/; m/\bstr=([\w\-]+)\b/; $1 }->($orig_url)
    . '/';

对于Ragepotatos帖子而言,这是一个更严格,不那么贪婪的正则表达式,未经测试:

Regex.Match(input.Replace("+", "-"),@"\bstr=(.*?)&").Groups[1].Value

答案 1 :(得分:2)

C#.NET

string input = "abc.aspx?str=blue+lagoon&id=1234";

string output = "/blogs/" + Regex.Match(input.Replace("+", "-"),@"str=(.*)&").Groups[1].Value + "/";