there is a string

string s = "http://captcha.site.com/captcha?key=5d11165823bed8a529794a6253f7ec6fab099f8f748424efddb2506f4dfe"; 

how to get everything that comes after "key ="? "5d11165823bed8a529794a6253f7ec6fab099f8f748424efddb2506f4dfe"

  • 2
    You do not need regulars here. The string.Split ('=') method is sufficient. - Alexander Petrov

4 answers 4

And let's try to do it right and securely! All means there.

 using System.Web; // ... var s = "http://captcha.site.com/captcha?key=5d11165823bed8a52979" + "4a6253f7ec6fab099f8f748424efddb2506f4dfe"; var uri = new Uri(s); var query = uri.Query; var parts = HttpUtility.ParseQueryString(query); var key = parts["key"]; 

You have to connect the assembly System.Web.

Why regulars if there is a ready-made parser?

  • Well, because I need a regular season) - inkorpus
  • @inkorpus: Regulars are not the best tool for parsing. - VladD
  • the string in the form of another method is returned to me, and now the key must be removed from the string) - inkorpus
  • 3
    @inkorpus: Well, yes, and the code from the answer does just that. This is parsing URI. Don't forget that the parts after = can be encoded ( https://www.google.com/search?q=%D0%BF%D1%8B%D1%89%D1%8C ), my code will automatically decode it. - VladD
  • 3
    By the way: Microsoft has a NuGet-package Microsoft.AspNet.WebApi.Client , which is PCL - in it the specified method is implemented as an extension method of the Uri class. Perhaps someone will be useful in the development of platforms other than Windows, so as not to fence the bike. ) - Sergey Rufanov
 [?&]key=(\w+) 

Take the first group.

    You can get regular expressions: https?:\/\/[^\s]+?key=([A-z0-9]*)

    • one
      error "Unrecognized control sequence" - inkorpus
     using System.Text.RegularExpressions; class Program { static void Main(string[] args) { const string InputStr = "http://captcha.site.com/captcha?key=5d11165823bed8a529794a6253f7ec6fab099f8f748424efddb2506f4dfe"; var match = Regex.Match(InputStr, "[\?&]key=(?<key>\\w+)"); var key = match.Groups["key"].Value; } } 
    • Made a small edit to improve the quality of the answer. - ReinRaus
    • @ReinRaus, it is better to check for a question or an ampersand, and not for a word boundary. By the way, I added this to my answer, but I didn’t even think about it at once. - Qwertiy
    • @Qwertiy yes, that's better. Only better to write it like this: [\?&] - ReinRaus
    • @ReinRaus, I agree. By the way, with square brackets, the screening question is not required. - Qwertiy
    • @Qwertiy yes, this is not necessary, I just used to escape meta-characters where they appear as literals. So then it is easier to perceive a regular expression. - ReinRaus pm