简体   繁体   中英

Retrive a Digit from a String using Regex

What I am trying to do is fairly simple, although I am running into difficulty. I have a string that is a url, it will have the format http://www.somedomain.com?id=someid what I want to retrive is the someid part. I figure I can use a regular expression but I'm not very good with them, this is what I tried:

Match match = Regex.Match(theString, @"*.?id=(/d.)");

I get a regex exception saying there was an error parsing the regex. The way I am reading this is "any number of characters" then the literal "?id=" followed "by any number of digits" . I put the digits in a group so I could pull them out. I'm not sure what is wrong with this. If anyone could tell me what I'm doing wrong I would appreciated it, thanks!

No need for Regex. Just use built-in utilities.

string query = new Uri("http://www.somedomain.com?id=someid").Query;
var dict = HttpUtility.ParseQueryString(query);

var value = dict["id"]

You've got a couple of errors in your regex. Try this:

Match match = Regex.Match(theString, @".*\?id=(\d+)");

Specifically, I:

  • changed *. to .* (dot matches all non-newline chars and * means zero or more of the preceding)
  • added a an escape sequence before the ? because the question mark is a special charcter in regular expressions. It means zero or one of the preceding.
  • changed /d. to \\d* (you had the slash going the wrong way and you used dot, which was explained above, instead of * which was also explained above)

尝试

var match = RegEx.Match(theString, @".*\?id=(\d+)");
  • The error is probably due to preceding * . The * character in regex matches zero or more occurrences of previous character; so it cannot be the first character.
  • Probably a typo, but shortcut for digit is \\d , not /d
  • . matches any character, you need to match one or more digits - so use a +
  • ? is a special character, so it needs to be escaped.

So it becomes:

Match match = Regex.Match(theString, @".*\?id=(\d+)");

That being said, regex is not the best tool for this; use a proper query string parser or things will eventually become difficult to manage.

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