2012-05-16 63 views
0

我有必要分析和转换某种URL的一部分,这里是我该怎么办,现在:在这种情况下正则表达式的正确使用是什么?

Regex s_re = new Regex(@"^/(lang_([^/]*)/)?([^/]*)([^\?]*)\??(.*)$", RegexOptions.IgnoreCase); 

const string Url = "..."; 

MatchCollection matches = s_re.Matches(Url); 
if(matches.Count==0) return false;//can't find matches 

string strLang = s_re.Replace(Url, @"$2"); 
string strAddr = s_re.Replace(Url, @"$3"); 

我是否正确理解,在这种情况下,我的URL解析3次(原比赛和每更换)。在最好的情况下,它只能被解析一次,结果应该被使用。

我怀疑,而不是以下呼吁“替换”我应该使用别的东西,但不能找到什么。

您能否提供建议?

谢谢。

回答

2

你应该做的是这样的:

Match match = regexData.Match(line); 
if (!match.Success) return false; 
string val1 = match.Groups[0].Value; 
string val2 = match.Groups[1].Value; 

此外,你可能想使用RegexOptions.CultureInvariant与RegexOptions.IgnoreCase,否则它使用当地的文化,而不是统一的外壳约定。 more on msdn

相关问题