正则表达式提取所有十进制值并进行迭代
本文关键字:迭代 十进制 提取 正则表达式 | 更新日期: 2023-09-27 18:18:23
假设我有字符串
<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
}
但是我如何提取小数?
我会使用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+
周围的括号!
试试这个大小:
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);
}
}
// 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