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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.