Py学习  »  Python

python 3中列表中的特定模式字符串

Gouse Shaik • 4 年前 • 786 次点击  

要求:使用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']
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38167
 
786 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Arkistarvh Kltzuonstev
Reply   •   1 楼
Arkistarvh Kltzuonstev    4 年前

另一个解决方案:

import re
exp = []
for i in ZTon:
    reg1 = re.search(r'.*?\--(.*)\--.*', i)
    reg2 = re.search(r'.*?\*(.*)\*.*', i)
    if reg1:
        exp.append(reg1[1])
    elif reg2:
        exp.append(reg2[1])

产量 :

[' and preferably only one ', 'right']
Andrej Kesely
Reply   •   2 楼
Andrej Kesely    4 年前
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']
SmartManoj
Reply   •   3 楼
SmartManoj    4 年前

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