如何从 python 中的文本中提取列数据(正则表达式)

How to extract column data from a text in python (regex)

假设我们有文本,其中 header 列以以下形式存储:

{|
|+ The table's caption
! scope="col" width="20"style="background-color:#cfcfcf;"align="center" | Column header 1
! scope="col" width="20"style="background-color:#ff55ff;"align="center" | Column header 2
! scope="col" | Column header 3
|-
! scope="row" | Row header 1
| Cell 2 || Cell 3
|-
! scope="row" | Row header A
| Cell B
| Cell C
|}

如何提取所有列 ([Column header 1, Column header 2, 列 header 3]) 来自 python?

中的文本
re.findall('*! scope="col" |', text, re.IGNORECASE)

但它没有发挥作用。

https://regex101.com/r/PLKREz/6

如何在 Python 中完成?

您可以在 scope="col":

的一行中找到最后一个 | 之后的所有子字符串
import re

data = """
{|
|+ The table's caption
! scope="col" width="20"style="background-color:#cfcfcf;"align="center" | Column header 1
! scope="col" width="20"style="background-color:#ff55ff;"align="center" | Column header 2
! scope="col" | Column header 3
|-
! scope="row" | Row header 1
| Cell 2 || Cell 3
|-
! scope="row" | Row header A
| Cell B
| Cell C
|}"""

print(re.findall(r'scope="col".*?\| ([^|]+)$', data, re.MULTILINE))

打印:

['Column header 1', 'Column header 2', 'Column header 3']