【问题标题】:Regex line by line正则表达式逐行
【发布时间】:2021-01-02 18:09:30
【问题描述】:
import re

P = re.compile(r'(?<=\{\n)((.*\n)*)(?=\})', re.MULTILINE)

text = r'''title {
      P 01
      X 02
    }'''
re.findall(P, text)

使用这段代码,我将括号中的所有内容都grep,但作为一个元素。

如何获得单行元素的列表,例如:

['P 01', 'X 02']

【问题讨论】:

  • 拆分结果匹配,re.search(P, text).group().splitlines()

标签: python-3.x regex list


【解决方案1】:

使用

import re

P = re.compile(r'\{(.*?)}', re.DOTALL)

text = r'''title {
      P 01
      X 02
    }'''
x = re.search(P, text)
if x:
    print([z.strip() for z in x.group(1).strip().splitlines()])

结果['P 01', 'X 02']

Python proof

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 2019-01-12
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多