[英]Python String split using a regex
例如,我们要拆分字符串多行
|---------------------------------------------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
使用什么是正确的正则表达式,或者有没有其他方法可以使用上面的格式进行拆分
您可以匹配线条并在组中捕获所需的部分,而不是使用拆分。
\|-{2,}[^-]+-{2,}([^-].*?)(?=\|)
解释
\\|
匹配|
-{2,}
匹配 2 个或更多-
[^-]+
匹配 1+ 次除-
之外的任何字符-{2,}
匹配 2 个或更多-
(
捕获组 1
[^-].*?
匹配除-
之外的任何字符,然后尽可能少地匹配任何字符)
关闭第 1 组(?=\\|)
正向预测,断言|
向右例子
import re
regex = r"\|-{2,}[^-]+-{2,}([^-].*?)(?=\|)"
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" \
"|"
str2 = re.findall(regex, str1);
print(str2[0])
print(str2[1])
输出
Content goes here, the quick brown fox jumps over the lazy dog
Content goes here, the quick brown fox jumps over the lazy dog
如果Title
应该是该行的一部分,另一种选择是使匹配更加精确。
\|-+Title\d+\([a-z]\)-+(.+?)(?=\||$)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.