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

5
  • stackoverflow.com/questions/4734116/… Commented Nov 6, 2019 at 12:32
  • 1
    string result = Regex.Match(source, @"q\s*=\s*(?<value>[0-9]+)").Groups["value"].Value; Commented Nov 6, 2019 at 12:35
  • 2
    I wouldn't look at it like getting a number from a string, instead I'd look at it like parsing a query string Commented Nov 6, 2019 at 12:35
  • 1
    This is a URI. Don't attempt to parse it manually. Instead, use the framework's built in tools to do that. Commented Nov 6, 2019 at 12:37
  • dotnetfiddle.net/le1Xec Commented Nov 6, 2019 at 12:48

4 Answers 4

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&amp;sid=&amp;q=1007040&amp;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"]);
Sign up to request clarification or add additional context in comments.

1 Comment

Canonical duplicate.
1

Consider using regular expressions

String str = "http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&amp;sid=&amp;q=1007040&amp;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
}

Comments

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&amp;sid=&amp;q=1007040&amp;a=2"));
string q = HttpUtility.ParseQueryString(uri.Query).Get("q");
int qint = int.Parse(q);

Comments

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!

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.