Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pick out a number from a string in C#

Tags:

c#

I have this string:

http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&sid=&q=1007040&a=2

How can I pick out the number between "q=" and "&amp" as an integer?

So in this case I want to get the number: 1007040

like image 848
Alan2 Avatar asked Dec 10 '22 01:12

Alan2


2 Answers

What you're actually doing is parsing a URI - so you can use the .Net library to do this properly as follows:

var str   = "http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&sid=&q=1007040&a=2";
var uri   = new Uri(str);
var query = uri.Query;
var dict  = System.Web.HttpUtility.ParseQueryString(query);

Console.WriteLine(dict["amp;q"]); // Outputs 1007040

If you want the numeric string as an integer then you'd need to parse it:

int number = int.Parse(dict["amp;q"]);
like image 127
Matthew Watson Avatar answered Dec 12 '22 14:12

Matthew Watson


Consider using regular expressions

String str = "http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&sid=&q=1007040&a=2";

Match match = Regex.Match(str, @"q=\d+&amp");

if (match.Success)
{
    string resultStr = match.Value.Replace("q=", String.Empty).Replace("&amp", String.Empty);
    int.TryParse(resultStr, out int result); // result = 1007040
}
like image 42
Linerath Avatar answered Dec 12 '22 14:12

Linerath