2

说我有字符串

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

但是我该如何取出小数点呢?

4

3 回答 3

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

于 2013-06-14T21:16:56.390 回答
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+

于 2013-06-14T21:18:22.870 回答
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);
        }
    }
于 2013-06-14T21:34:00.423 回答