Question

I have the following line from a string:

colors numResults="100" totalResults="6806926"

I want to extract the value 6806926 from the above string How is it possible?

So far, I have used StringReader to read the entire string line by line. Then what should I do?

Was it helpful?

Solution 2

Consider the this is in Mytext of string type variable

now

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

//the function indexof will return the point wheres the value start, //and 7 is a length of charactors that you want to extract

I am using similar of this ........

OTHER TIPS

I'm sure there's also a regex, but this string approach should work also:

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

Demo

You can read with Linq2Xml, numResults and totalResults are Attributes, and <colors numResults="100" totalResults="6806926"> is Element, so you can simply get it by nmyXmlElement.Attributes("totalResults").

This function will split the string into a list of key value pairs which you can then pull out whatever you require

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

You can use regular expressions:

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

Be sure to have this included:

using System.Text.RegularExpressions;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top