Python regular expressions match words in the middle as optional

Python regular expressions match words in the middle as optional … here is a solution to the problem.

Python regular expressions match words in the middle as optional

I have different regular expression patterns with a lot of optional parts 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 do this, I print out “not matching”, but if I change “something” to “so”, I print out “less useful”, and

the “so” part is optional, meaning that if it doesn’t exist, then “no” and “useful” should still match

Another pattern matching I need is this:

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: Okay, so I’ll rephrase the question in Part II here:

Wiktor provides this regular expression (not|maybe)(?:(?:so)?. *?)? (Useful| good| correct) (?: at(?: all)?)?

This marks the following occurrence on this regular expression 101 website:

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

But I also need to match/group in case one or more 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 want to set a group for “at”, “all” because they appear in the text above.

If no optional parts are found, these groups should not be returned, but only the remaining parts that match mandatory words such as “not”, “useful”, and so on

Solution

Well, I figured it out now 🙂

Use this regular expression:

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

I

was able to capture what I wanted. Thanks wiktor for helping me and providing this regex online site, which is very helpful for quickly testing your regex patterns.

Related Problems and Solutions