首页 > 解决方案 > 从 txt 下方捕获行片段

问题描述

我正在尝试使用复制的 PDF 中的正则表达式从 txt 中的表中读取并获取特定值。

例如:

DADOS DO FABRICANTE
* CNPJ/CPF           UF    Quantidade Peso Líquido(kg)   Vl.Moeda
- 99.999.999/9999-99 MN    4,00000    212,00000          250.400,00
Obs:

在上面的文字中,我想从 UF 获得价值,即 MN 和其他当然像 Vl.Moeda

我尝试了这个正则表达式,但效果不佳:

[*\n\r\s*]UF\s *.*[^\w]

标签: c#regex

解决方案


这有点困难,而您的尝试看起来很棒。我的猜测是我们可能想要捕获UF Vl.Moeda关联的值,我们也许可以这样做,也许使用这个表达式:

\b([A-Z]{2})\b\s{2,}.*\s{2,}(.+)

我们将在其中包含 a\s{2,}以使其他类似文本失败,然后在([A-Z]{2})and中捕获我们想要的输出(.+)

演示

测试

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\b([A-Z]{2})\b\s{2,}.*\s{2,}(.+)";
        string input = @"DADOS DO FABRICANTE
* CNPJ/CPF           UF    Quantidade Peso Líquido(kg)   Vl.Moeda
- 99.999.999/9999-99 MN    4,00000    212,00000          250.400,00
Obs:
- 99.999.999/9999-99 AB    4,00000    212,00000          250.400,00000
Obs:
- 99.999.999/9999-99 XZ    4,00000    212,00000          250.400,00000
Obs:";
        RegexOptions options = RegexOptions.Multiline;
        
        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

正则表达式电路

jex.im可视化正则表达式:

在此处输入图像描述


推荐阅读