使用正则表达式访问文本中的多行并在python中迭代

使用正则表达式访问文本中的多行并在python中迭代,python,regex,Python,Regex,我有一个文本文件,它是从发票/PO pdf文件转换而来的。我需要使用正则表达式从中提取产品详细信息。我面临的问题是,我可以很容易地提取单个产品的细节。但是,由于分析了许多发票(不是一次分析),我无法预测发票中的产品数量。所以,我如何确定有多少产品将在那里,并通过它迭代,并采取所有产品的细节 以下是单个产品的发票文本示例: 下面给出了一个包含多个产品的产品: 现在,我使用的正则表达式和代码如下: line_match = re.compile(r'UOM\s\d\s+([\w.]+)\s([\w\

我有一个文本文件,它是从发票/PO pdf文件转换而来的。我需要使用正则表达式从中提取产品详细信息。我面临的问题是,我可以很容易地提取单个产品的细节。但是,由于分析了许多发票(不是一次分析),我无法预测发票中的产品数量。所以,我如何确定有多少产品将在那里,并通过它迭代,并采取所有产品的细节

以下是单个产品的发票文本示例: 下面给出了一个包含多个产品的产品: 现在,我使用的正则表达式和代码如下:

line_match = re.compile(r'UOM\s\d\s+([\w.]+)\s([\w\s\-]+[\s])([0-9.]+)\s([\w]+)\n([\w\/\s]+[\n])')

line = line_match.search(text)
    
print("Product description : " + line.group(2) + line.group(5))
print("Quantity : " + line.group(3))
您可以使用和使用
\G
锚来获得迭代匹配

图案

  • (?:
    非捕获组
    • UOM\s
      匹配UOM和空格字符
    • |
    • \G(?!^)
      在上一次匹配结束时而不是开始时定位
  • 关闭组
  • \d\s+
    匹配数字和1+空格字符
  • ([\w.]+)\s
    捕获组1匹配单词字符或点和空格字符
  • ([\w\s-]+\s)
    捕获组2匹配单词/空格字符或
    -
    和结尾的空格字符
  • ([0-9.]+)\s
    捕获组3匹配数字或
    和空格字符
  • (\w+)\n
    捕获组4匹配单词字符和换行符
  • ([\w/\s]+\n)
    捕获组5匹配单词/空格字符或
    /
    和换行符
|

示例代码

输出


您的文件中是否真的有这些

,或者试图在
StackOverflow
中添加换行符?很抱歉。我想换行如果你能用的话,你可以用
(?:UOM\s |\G(?!^))\d\s+([\w.]+)\s([\w\s-]+\s)([0-9.]+)\s(\w+)\n([\w/\s]+\n)
谢谢,这很有效。但我如何从中提取每个匹配项?@zuestech我添加了一个答案,并解释了如何获取匹配项。
Item SKU Product Desc. Qty UOM
1 L465.0001354266 Yoghurt Passionfruit Organic 4.00 PC
Vegan 1kg
2 L465.0001354264 Yoghurt Plain Organic Vegan 4.00 PC
1kg
line_match = re.compile(r'UOM\s\d\s+([\w.]+)\s([\w\s\-]+[\s])([0-9.]+)\s([\w]+)\n([\w\/\s]+[\n])')

line = line_match.search(text)
    
print("Product description : " + line.group(2) + line.group(5))
print("Quantity : " + line.group(3))
(?:UOM\s|\G(?!^))\d\s+([\w.]+)\s([\w\s-]+\s)([0-9.]+)\s(\w+)\n([\w/\s]+\n)
import regex

pattern = r"(?:UOM\s|\G(?!^))\d\s+([\w.]+)\s([\w\s-]+\s)([0-9.]+)\s(\w+)\n([\w/\s]+\n)"

test_str = ("Item SKU Product Desc. Qty UOM\n"
            "1 _L180.0001352879 Clam Tuatua Medium 20- 1.00 cs\n"
            "34pc/Kg 15kg/CS\n\n\n\n"
            "Item SKU Product Desc. Qty UOM\n"
            "1 L465.0001354266 Yoghurt Passionfruit Organic 4.00 PC\n"
            "Vegan 1kg\n"
            "2 L465.0001354264 Yoghurt Plain Organic Vegan 4.00 PC\n"
            "1kg\n\n\n")


matches = regex.finditer(pattern, test_str)

for matchNum, match in enumerate(matches, start=1):
    print("Product description : " + match.group(2) + match.group(5))
    print("Quantity : " + match.group(3))
Product description : Clam Tuatua Medium 20- 34pc/Kg 15kg/CS
Quantity : 1.00
Product description : Yoghurt Passionfruit Organic Vegan 1kg
Quantity : 4.00
Product description : Yoghurt Plain Organic Vegan 1kg
Quantity : 4.00