c# - RegEx 捕获重复字段?

标签 c# regex

我有一个缓冲区,我正在尝试使用正则表达式进行解析。

这里是缓冲区的例子:

DATA#ALPHAONE;BETATWO.CHARLIETHREE!

格式是:缓冲区总是以“DATA#”开头,作为文字头。 之后,它将有一个或多个文本字段,由分号、句点或感叹号分隔。

到目前为止,我的正则表达式模式(在 C# 中)是:

string singleFieldPattern = "(?'Field'.*?)(?'Separator'[;.!])";
string fullBufferPattern = "(?'Header'DATA#)(" + singleFieldPattern + ")+";

当我尝试转储匹配的数据时出现问题:

Regex response = new Regex(fullBufferPattern);
string example = "DATA#ALPHAONE;BETATWO.CHARLIETHREE!";

Debug.WriteLine("RegEx Matches?: {0}", response.IsMatch(example));  
foreach (Match m in response.Matches(example))
{
    foreach(string s in new string[]{"Header", "Field", "Separator"}) 
    {
        Debug.WriteLine("{0} : {1}", s, m.Groups[s]);
    }
}

唯一的输出是:

RegEx Matches?: True
Header : DATA#
Field : CHARLIETHREE
Separator : !

我希望输出是:

RegEx Matches?: True
Header : DATA#
Field : ALPHAONE
Separator : ;
Field : BETATWO
Separator : .
Field : CHARLIETHREE
Separator : !

我的表达式没有得到较早的字段,ALPHAONEBETATWO(以及它们的分隔符 ;) 如我所愿。它只捕获了最后一个字段 (CHARLIETHREE)。

如何获取所有匹配 singleFieldPattern 的部分?


出于问题的目的,我在上面简化了我的数据格式,但由于有些人想要真实数据,这里更接近实际数据:

(注意:[ ] 中的值是不可打印的单字节,空格只是为了清楚起见。)

例子:

[SYN] % SYSNAMScanner[ACK]; BAUDRATE57600[ACK]; CTRLMODEXON[ACK];

翻译:
系统名称 (SYSNAM) 是“扫描仪”
波特率为57,600
流量控制是 XON

最佳答案

这段 LINQ 会将正则表达式中的字段和分隔符配对在一起:

var ms = response.Matches(example);
foreach (Match m in ms)
{
    string header = m.Groups["Header"].Value;
    Debug.WriteLine("Header : " + header);
    var pairs = m.Groups["Field"].Captures.Cast<Capture>().Zip(
                    m.Groups["Separator"].Captures.Cast<Capture>(),
                    (f, s) => new { Field = f.Value, Separator = s.Value });
    foreach (var pair in pairs)
    {
        Debug.WriteLine(pair.ToString());
    }
}

这个输出:

Header : DATA#
{ Field = ALPHAONE, Separator = ; }
{ Field = BETATWO, Separator = . }
{ Field = CHARLIETHREE, Separator = ! }

关于c# - RegEx 捕获重复字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620167/

相关文章:

c# - RestSharp - XmlSerializer 不使用 DateFormat 属性

Javascript Replace() 在 iPhone 上对于长字符串表现不佳

Python:用字典中的实体替换某些 Unicode 实体

c# - Coverity、Enumerable.Where(this ...) 和 IDisposable

c# - 如何处理 Task.Run 异常

c# - ServiceBus 抛出 401 未授权错误

java - C# 中 Java 的 >>>= 是什么

python - 在字符串末尾匹配一系列(非嵌套)平衡括号

php - preg_match() : Compilation failed: invalid range in character class at offset

php - PHP正则表达式以匹配Vimeo文本或html链接