【发布时间】:2021-03-06 05:23:35
【问题描述】:
例如我们想将一个字符串分割成多行
|---------------------------------------------Title1(a)---------------------------------------------
Content goes here, the quick brown fox jumps over the lazy dog
|---------------------------------------------Title1(b)----------------------------------------------
Content goes here, the quick brown fox jumps over the lazy dog
这是我们使用正则表达式代码进行的 python 拆分
import re
str1 = "|---------------------------------------------Title1(a)---------------------------------------------" \
"" \
"Content goes here, the quick brown fox jumps over the lazy dog" \
"" \
"|---------------------------------------------Title1(b)----------------------------------------------" \
"" \
"Content goes here, the quick brown fox jumps over the lazy dog" \
"|"
print(str1)
str2 = re.split("\|---------------------------------------------", str1)
print(str2)
我们希望输出只包含
str2[0]:
Content goes here, the quick brown fox jumps over the lazy dog
str2[1]:
Content goes here, the quick brown fox jumps over the lazy dog
什么是正确的正则表达式,或者有没有其他方法可以使用上述格式进行拆分
【问题讨论】:
-
可能是
re.split(r'\s*^\|---.*\s*', text)?不过,您仍然需要摆脱第一个空项目。此外,str1在您的代码中不包含换行符。 -
也许你想要的只是所有不以
|---开头的非空行?str2 = [line for line in str1.splitlines() if not line.startswith('|---') and line.strip()] -
您可以使用
\|-+Title\d+\([a-z]\)-+(.+?)(?=\||$)regex101.com/r/R6kwim/1 然后使用 re.findall 并根据需要按索引获取值。见ideone.com/vHbRSa -
或者如果必须在末尾有一个
|和一个除 - 之外的任何其他字符,用于标题和内容\|-{2,}[^-]+-{2,}([^-].*?)(?=\|)regex101.com/r/J501Ea/1 -
这能回答你的问题吗? Split string based on a regular expression
标签: python python-3.x regex