gpt4 book ai didi

python-re.findall 如何将内容分成组

转载 作者:行者123 更新时间:2023-12-01 04:54:31 26 4
gpt4 key购买 nike

我需要一些有关 re.findall 方法的正则表达式如何工作的说明。

pattern = re.compile(r'(?<=\\\\\[-16pt]\n)([\s\S]*?)(?=\\\\\n\\thinhline)')
content= ' '.join(re.findall(pattern, content))

因此,上面打印了该模式与开头为 \\[-16pt] 和结尾为 '\\n Thinhline' 以及其后的所有文本匹配的所有内容。如果我有与模式匹配的以下内容:

\\[-16pt]
x = 10
print ("hi")
\\
\thinhline
\\[-16pt]
y = 3
print ("bye")
\\
\thinhline
\\[-16pt]
z = 7
print ("zap")
\\
\thinhline
This is random text.
All of this is matched by re.findall, even though it is not included within the pattern.
xyz = "xyz"

我如何区分每个组,以便我能够独立编辑它们:

第 1 组:

x = 10
print ("hi")

第 2 组:

y = 3
print ("bye")

第 3 组:

z = 7
print ("zap")

并且后面没有匹配任何额外的内容?

谢谢。

最佳答案

考虑以下可运行程序:

import re

content="""\\[-16pt]
x = 10
print ("hi")
\\
thinhline
\\[-16pt]
y = 3
print ("bye")
\\
thinhline
\\[-16pt]
z = 7
print ("zap")
\\
thinhline
This is random text.
"""

pattern = re.compile(r"""(\\\[-16pt]\n) # Start. Don't technically need to capture.
(.*?) # What we want. Must capture ;)
(\n\\\nthinhline) # End. Also don't really need to capture
""", re.X | re.DOTALL)

for m in pattern.finditer(content):
print("Matched:\n----\n%s\n----\n" % m.group(2))

运行时输出:

Matched:
----
x = 10
print ("hi")
----

Matched:
----
y = 3
print ("bye")
----

Matched:
----
z = 7
print ("zap")
----

注释:

  • 通过使用 re.X 选项,表达式可以是多行并带有注释
  • 通过使用re.DOTALL选项,可以删除过多的反斜杠和“.*?”组(即“非贪婪地获取每个字符,直到下一场比赛”)将包含换行符。
  • 我使用了 finditer 而不是 findall ...从技术上讲,它已经消失了从你的问题来看,但你想处理每场比赛,所以我想了想是一个很好的方法。
  • 我将 \t 标签从 thinhline 上取下,因为我不确定它是否是意味着是制表符或反冲然后-t。对以上影响不大但只是想澄清一下。
  • 我捕获开始组和结束组仅用于演示。只有中间确实需要组。

关于python-re.findall 如何将内容分成组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27745894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com