简体   繁体   English

在这种情况下正确使用正则表达式是什么?

[英]What is the proper use of Regex in this situation?

I have necessity to parse and convert some kind of URL part, here is how I do that now: 我有必要解析和转换某种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");

Am I correctly understand that in this case my URL is parsed 3 times (original match and each replace). 我是否正确理解,在这种情况下,我的URL被解析3次(原始匹配和每次替换)。 And in the best case it should be parsed only once and the result should be used. 在最好的情况下,它应该只被解析一次,并且应该使用结果。

I suspect that instead of following call to "Replace" I should use something else, but can't find what exactly. 我怀疑,而不是跟随“替换”调用,我应该使用其他东西,但无法找到究竟是什么。

Could you please advise? 您能否提一些建议?

Thanks. 谢谢。

You should do it like this: 你应该这样做:

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

Also, you probably want to use RegexOptions.CultureInvariant with that RegexOptions.IgnoreCase because otherwise it uses casing conventions of local culture and not unicode. 此外,您可能希望将RegexOptions.CultureInvariant与RegexOptions.IgnoreCase一起使用,因为否则它使用本地文化的套管约定而不是unicode。 more on msdn 更多关于msdn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM