How do I validate this string that can be enclosed between one or more spaces (but never none) via a regex?

Viewed 47

This is my code:

input_text_l = "hjahsdjhas pal sahashjas"

regex= re.compile(r"\s*\¿?(?:pal1|pal2|pal)\s*\??") #THIS IS THE REGEX THAT DOES NOT WORK CORRECTLY

if regex.search(input_text_l):

    not_tag = " ".join(regex_tag.split(input_text_l))
    #print(not_tag)

else:
    pass

And this is a simple diagram on how the regular expression should work.

enter image description here

I hope you can help me with this.

1 Answers

Don't do complicated things: \s+…\s+ is sufficient. + is actually exactly what you wrote: "one or more but not none"

import re
re.search('\s+pal\s+', input_text_l)

or for several patterns:

re.search('\s+(?:pal1|pal2|pal)\s+', input_text_l)

Example:

>>> input_text_l = "hjahsdjhas pal sahashjas"
>>> re.search('\s+(?:pal1|pal2|pal)\s+', input_text_l)
<re.Match object; span=(10, 15), match=' pal '>
Related