简体   繁体   中英

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:

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). 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. more on msdn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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