lundi 5 mars 2018

python regex match with words in between as optional

i have different regex patterns with a lot of optional parts in it. i tried with this online python tool to test my regex patterns but it doesnt work:

http://www.tutorialspoint.com/execute_python_online.php?PID=0Bw_CjBb95KQMSllMVktXUGZJcmc

import re

s = 'not something useful at all'

p=re.compile(r'not (?:so)? (useful|good|correct)')

if p.search(s) != None:
    print(p.search(s).group(0))
else:
    print("no match")

so if i execute this i get the "no match" printed but if i change 'something' to 'so' then i get printed "not so useful" the 'so' part is optional meaning if it is not there, then "not" and "useful" should still match

also another pattern match i need is something like:

import re

s = 'not random_text_inbetween useful random_text_inbetween at random_text_inbetween all'

p=re.compile(r'(not|maybe) (?:so)? (useful|good|correct) (?:at)? (?:all)?')

if p.search(s) != None:
    print(p.search(s).group(0))
else:
    print("no match")

so here i have certain mandatory words like (not OR maybe) or (useful OR good OR correct) and certain optional parts like (so, at , all) and both mandatory and optional parts can have text or numbers which are in between. i need a regex which matches if e.g.:

mandatory + optional:text_in_between + optional:word + optional:text_in_between + mandatory OR optional:word

Aucun commentaire:

Enregistrer un commentaire