簡體   English   中英

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

[英]Specific pattern strings from List in python 3

要求:使用正則表達式只希望從輸入列表中提取特定的字符串,即字符串“-”和“ *”之間。 下面是代碼片段

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

使用正則表達式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM