Extract a digit from a string using Regex

What I'm trying to do is pretty simple, although I run into difficulties. I have a string that is a URL, it will be in the format http://www.somedomain.com?id=someid , which I want to extract, this is some part. I suppose I can use regex, but I'm not very good with them, here is what I tried:

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

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

+4
source share
4 answers

No need for regular expression. Just use the built-in utilities.

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

You have a few errors in your regex. Try the following:

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

In particular, I:

  • changed *. on .* (the dot matches all characters other than the newline, and * means zero or more previous)
  • added escape sequence before ? because the question mark is a special character in regular expressions. This means zero or one of the previous ones.
  • changed /d. to \d* (you had the wrong slash, and you used the dot that was explained above, instead of * , which was also described above).
+4
source

Try

 var match = RegEx.Match(theString, @".*\?id=(\d+)"); 
+2
source
  • The error is probably related to the previous * . The * character in a regular expression matches zero or more occurrences of the previous character; therefore, he cannot be the first character.
  • Maybe a typo, but a shortcut for the \d , not /d
  • . matches any character, you need to match one or more digits - so use +
  • ? is a special character, so it must be escaped.

So it will be:

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

However, regular expression is not the best tool for this; use the correct query string parser, otherwise everything will be difficult to manage.

+1
source

Source: https://habr.com/ru/post/1437646/


All Articles