RegularExpressions提取所有十进制值并迭代

时间:2013-06-14 21:11:36

标签: c# regex

说我有字符串

<Records>
         <record id='818591'/>
         <record id='818592'/>
         <record id='818593'/>
         <record id='818594'/>
         <record id='818595'/>
         <record id='818596'/>
         <record id='818597'/>
         <record id='818598'/>
</Records>

如何在C#中提取并迭代每个“id”值。

我假设它会是这样的:

foreach (Match match in Regex.Matches(archerResponse,@"<Records>(<record id='\d*'/>)*</Records>"))
{
       //get value
}

但我如何才能拉出小数?

3 个答案:

答案 0 :(得分:1)

// main program
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            XDocument doc = XDocument.Parse(@"<Records> <record id='818591'/> <record id='818592'/> <record id='818593'/> <record id='818594'/> <record id='818595'/> <record id='818596'/> <record id='818597'/> <record id='818598'/></Records>");

            foreach (string s in doc.Descendants().Attributes("id").Select(a => a.Value))
            {
                Console.WriteLine(s);
            }
        }
    }
}

或者如果你已经开始使用正则表达式...以下是你可以使用的正则表达式。

"id='(.*?)'"

http://rubular.com/r/Pd4NbqDeVw

答案 1 :(得分:1)

我使用XML解析器:

XElement.Parse(archerResponse)
    .Elements("record")
    .SelectMany(n => n.Attributes("id"))
    .Select(x => x.Value); //gives you a collection of the items needed.

如果你真的想要正则表达式,请使用捕获组:

foreach (Match match in Regex.Matches(archerResponse,@"<Records>(<record id='(\d+)'/>)*</Records>"))
{
    string result = match.Groups[0];
}

(请注意\d+周围的括号!)

答案 2 :(得分:1)

尝试使用此尺寸:

    string text =
        @"<Records><record id='818591'/><record id='818592'/><record id='818593'/><record id='818594'/><record id='818595'/><record id='818596'/><record id='818597'/><record id='818598'/></Records>";

    MatchCollection matches = Regex.Matches(text, @"[0-9]+(\.[0-9][0-9]?)?");

    if(matches.Count > 0)
    {
        foreach (var value in matches)
        {
            Console.Write(value);
        }
    }