Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex match with words in between as optional

Tags:

python

regex

I have different regex patterns with a lot of optional parts in it, but it doesn't work:

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

Edit: ok so i will rephrase the question for the second part here:

wiktor provided this regex (not|maybe)(?:(?: so)?.*?)? (useful|good|correct)(?: at(?: all)?)?

this marks on this regex 101 website the following matches:

Match 1
Full match  0-32    `not random_text_inbetween useful`
Group 1.    0-3 `not`
Group 2.    26-32   `useful`

but what i also need are matches/groups in case one or more of the optional parts are also in the string:

"not random_text_inbetween useful random_text_inbetween at random_text_inbetween all"

so in this example i would like to have a group for "at" , "all" because they appear in the text above.

if the optional parts are not found then these groups should simply not be returned but only the remaining matches for the mandatory words like "not" , "useful"

like image 231
friggler Avatar asked May 10 '26 03:05

friggler


1 Answers

Ok so i figured it out now :-)

with this regex:

(not) (?:[^|]+) (useful) (?:[^|]+) (at)? (?:[^|]+) (all)?

i am able to capture what i want. thanks wiktor for helping me and providing this regex online website which is really helpful to quickly test your regex patterns.

like image 56
friggler Avatar answered May 12 '26 15:05

friggler