简体   繁体   English

如何从 C# 中的字符串中提取一个数字

[英]How can I pick out a number from a string in 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?如何选择“q=”和“&amp”之间的数字作为 integer?

So in this case I want to get the number: 1007040所以在这种情况下,我想得到号码:1007040

What you're actually doing is parsing a URI - so you can use the.Net library to do this properly as follows:您实际上正在做的是解析 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

If you want the numeric string as an integer then you'd need to parse it:如果您希望数字字符串为 integer,那么您需要解析它:

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

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
}

Seems like you want a query parameter for a uri that's html encoded.好像您想要一个 uri 的查询参数,它是 html 编码的。 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);

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!绝对没有错误检查!

Find the numbers in the query string URL查找查询字符串 URL 中的数字

 Uri myUri = new Uri("http://www.edrdg.org/jmdictdb/cgi-bin/edform.py?svc=jmdict&sid=&q=1007040&a=2");
string param = HttpUtility.ParseQueryString(myUri.Query).Get("q");
Console.WriteLine(param); // Outputs 1007040

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM