C# 如何从C中的字符串中选择一个数字#

C# 如何从C中的字符串中选择一个数字#,c#,C#,我有这个字符串: http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&sid=&q=1007040&a=2 如何将“q=”和“&”之间的数字选为整数 因此,在本例中,我想得到数字:1007040考虑使用正则表达式 String str = "http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&s

我有这个字符串:

http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&sid=&q=1007040&a=2
如何将“q=”和“&”之间的数字选为整数


因此,在本例中,我想得到数字:1007040考虑使用正则表达式

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
}

实际上,您所做的是解析URI—因此您可以使用.Net库正确地执行此操作,如下所示:

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
如果希望数字字符串为整数,则需要对其进行解析:

int number = int.Parse(dict["amp;q"]);

似乎您需要一个html编码的uri的查询参数。你可以做:

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);

使用组的正则表达式方法:

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

检查时绝对没有错误

string result=Regex.Match(源代码,@“q\s*=\s*(?[0-9]+)”)。组[“value”]。值我不会把它看成是从字符串中获取一个数字,相反,我会把它看成是一个URI。不要试图手动解析它。相反,请使用框架的内置工具来实现这一点。