1

Requirement:using regex want to fetch only specific strings i.e. 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']
3
  • What have you tried so far? Where did you get stuck? Commented Jun 10, 2019 at 14:22
  • Please share the code you tried to fetch strings, not the usage of strip(). Commented Jun 10, 2019 at 14:23
  • 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) Commented Jun 10, 2019 at 14:28

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

Comments

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

Prints:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.