python3中列表中的特定模式字符串

2024-09-28 03:20:32 发布

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

回复quirement:using regex 只想从输入列表中获取特定字符串,即“-”和“*”符号之间的字符串。下面是代码片段

    ZTon = ['one-- and preferably only one --obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.']
ZTon = [ line.strip() for line in ZTon]
print (ZTon)
r = re.compile(".^--")
portion = list(filter(r.match, ZTon)) # Read Note
print (portion)

预期响应:

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

Tags: and字符串rightonlyislineoneprint
2条回答
import re

ZTon = ['one  and preferably only one  obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.']

def gen(lst):
    for s in lst:
        s = ''.join(i.strip() for g in re.findall(r'(?:-([^-]+)-)|(?:\*([^*]+)\*)', s) for i in g)
        if s:
            yield s

print(list(gen(ZTon)))

印刷品:

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

使用正则表达式

import re
ZTon = ['one  and preferably only one  obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.']
pattern=r'( |\*)(.*)\1'
l=[]
for line in ZTon:
    s=re.search(pattern,line)
    if s:l.append(s.group(2).strip())
print (l)
# ['and preferably only one', 'right']

相关问题 更多 >

    热门问题