简体   繁体   English

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

[英]Specific pattern strings from List in python 3

Requirement:using regex want to fetch only specific strings ie string betwee "-" and "*" symbols from input list. 要求:使用正则表达式只希望从输入列表中提取特定的字符串,即字符串“-”和“ *”之间。 Below is the code snippet 下面是代码片段

    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)

Expected response: 预期回应:

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

Using regex 使用正则表达式

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)))

Prints: 打印:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM