4

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!

4 Answers 4

6

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"]
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

2

Try

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

Comments

1
  • 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.