5

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

Alan2
  • 23,493
  • 79
  • 256
  • 450

4 Answers4

10

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"]);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

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
}
Linerath
  • 13
  • 1
  • 2
1

Seems like you want a query parameter for a uri that's html encoded. You could do:

Uri uri = new Uri(HttpUtility.HtmlDecode("http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&sid=&q=1007040&a=2"));
string q = HttpUtility.ParseQueryString(uri.Query).Get("q");
int qint = int.Parse(q);
NotFound
  • 5,005
  • 2
  • 13
  • 33
1

A regex approach using groups:

public int GetInt(string str)
{
    var match = Regex.Match(str,@"q=(\d*)&amp");
    return int.Parse(match.Groups[1].Value);
}

Absolutely no error checking in that!

Tim Rutter
  • 4,549
  • 3
  • 23
  • 47