python 3中List中的特定模式字符串

时间:2019-06-10 14:19:07

标签: python 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']

2 个答案:

答案 0 :(得分:1)

使用正则表达式

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']

答案 1 :(得分:1)

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']