C#读取字符串中的特定值

本文关键字:读取 字符串 | 更新日期: 2023-09-27 18:20:47

我有一个字符串中的以下行:

colors numResults="100" totalResults="6806926"

我想从上面的字符串中提取值6806926这怎么可能?

到目前为止,我已经使用StringReader逐行读取了整个字符串。那我该怎么办?

C#读取字符串中的特定值

我相信还有一个正则表达式,但这种string方法也应该有效:

string xmlLine = "[<colors numResults='"100'" totalResults='"6806926'">]";
string pattern = "totalResults='"";
int startIndex = xmlLine.IndexOf(pattern);
if(startIndex >= 0)
{
    startIndex += pattern.Length;
    int endIndex = xmlLine.IndexOf("'"", startIndex); 
    if(endIndex >= 0)
    {
        string token = xmlLine.Substring(startIndex,endIndex - startIndex);
        // if you want to calculate with it
        int totalResults = int.Parse( token );
    }
}

演示

考虑字符串类型变量的Mytext中的this

现在

Mytext.Substring(Mytext.indexof("totalResults="),7); 

//函数indexof将返回值开始的点,//7是要提取的字符长度

我正在使用类似的。。。。。。。。

您可以使用Linq2Xml进行读取,numResults和totalResults是属性<colors numResults="100" totalResults="6806926">元素。因此,您只需通过n个myXmlElement.Attributes("totalResults")即可获得它。

此函数将字符串拆分为键值对列表,然后可以提取出所需的

        static List<KeyValuePair<string, string>>  getItems(string s)
    {
        var retVal = new List<KeyValuePair<String, string>>();
        var items = s.Split(' ');
        foreach (var item in items.Where(x => x.Contains("=")))
        {
            retVal.Add(new KeyValuePair<string, string>( item.Split('=')[0], item.Split('=')[1].Replace("'"", "") ));
        }
        return retVal;
    }

您可以使用正则表达式:

string input = "colors numResults='"100'" totalResults='"6806926'"";
string pattern = "totalResults='"(?<results>''d+?)'"";
Match result = new Regex(pattern).Match(input);
Console.WriteLine(result.Groups["results"]);

请确保包括以下内容:

using System.Text.RegularExpressions;