python - 如何编写正则表达式以在 python 中使用 re.split

标签 python regex

我有这样一个字符串:

----------

FT Weekend

----------

Why do we run marathons?
Are marathons and cycling races about more than exercise? What does the 
literature of endurance tell us about our thirst for self-imposed hardship? 

我想删除从 ------------ 到下一个 ------------ 的部分。

我一直在使用re.sub:

pattern =r"-+\n.+\n-+"
re.sub(pattern, '', thestring)

最佳答案

pattern =r"-+\n.+?\n-+"
re.sub(pattern, '', thestring,flags=re.DOTALL)

只需使用 DOTALL 标志。您的正则表达式的问题是默认情况下 \n 不匹配。因此您需要明确添加标志 DOTALL 使其匹配 \n

查看演示。

https://regex101.com/r/hR7tH4/24

pattern =r"-+\n[\s\S]+?\n-+"
re.sub(pattern, '', thestring)

如果你不想添加标志

关于python - 如何编写正则表达式以在 python 中使用 re.split,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403194/

相关文章:

python - 如何在 django 中使用主键对 url 进行反向操作

python - 如何获得月份的完整拼写是在 python pandas 中使用日历模块?

Python - 替换多个文件中的数字

python - 使用 PyQt 和 Qthreads 的 GUI 非常缓慢

java - 如何从字符串中删除此网址?

javascript - 如何在 Javascript 中使用 .split 最好地解析文本文件

javascript - 如何解析 Objective-C 中 JavaScript 赋值语句中的值

python - 将新项目 append 到列表时出现问题

python - 在 for 循环中将字典添加到列表中,每次运行的最后一个 dict.key 的值未正确添加

regex - 有没有办法缩短这个正则表达式?