在python3中,使用regex过滤文本部分嵌入到或*之间的行

2024-09-28 03:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

string1 = '''
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

所需输出:

^{pr2}$

我用了下面提到的正则表达式

portions=re.findall(r"[/*-](\S.*)[/*-]",zenPython)
print(portions)

但是我没有得到想要的结果,我的输出:

['- and preferably only one -', 'right']

Tags: andofthetoisitbeone
2条回答

使用正则表达式获得正确答案

['and preferably only one', 'right']

尝试下面的代码

^{pr2}$

您可以稍微更改正则表达式:

zenPython = '''
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one  and preferably only one  obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea   let's do more of those!
'''

import re

portions=re.findall(r"[-*] ?([^-*].*?) ?[-*]",zenPython)
print(portions)

输出:

^{pr2}$

regex r"[-*] ?([^-*].*?) ?[-*]"将查找:

 [-*] ?               - or * followed by optional space
 ([^-*].*?)           grouping any character different then - or * as few as possible
  ?[-*]               optional space followed by - or * 

这对以下文本无效:

This is  - not going-to work   example. 

在这里玩正则表达式:https://regex101.com/r/wNBJEE/1

相关问题 更多 >

    热门问题