ragnar723
ragnar723

Reputation: 1

How to create a Regex based on user input (Python)

I am fairly new to Python, and I am learning about Regexes right now, which has been a bit of a challenge for me. My issue right now is I am working on a problem that is to create a function that is a Regex version of the strip() string method.

My problem is that I can't figure out how to convert a character that user inputs into a regex without listing out every possibility in the program with if statements. For instance:

def regexStrip(string, char):
    if char = 'a' or 'b' or 'c' etc...
        charRegex = re.compile(r'^[a-z]+')

This isn't my full program just a few lines to demonstrate what I'm talking about. I was wondering if anyone could help me in finding a more efficient way to convert user input into a Regex.

Upvotes: 0

Views: 2412

Answers (1)

Corentin Limier
Corentin Limier

Reputation: 5006

You can use braces inside strings and the format function to build the regular expression.

def regexStrip(string, char=' '):
    #Removes the characters at the beginning of the string
    striped_left = re.sub('^{}*'.format(char), '', string)
    #Removes the characters at the end of the string
    striped = re.sub('{}*$'.format(char), '', striped_left)
    return striped

The strip method in python allows to use multiples chars, for example you can do 'hello world'.strip('held') and it will return 'o wor'

To perform this, you can do :

def regexStrip(string, chars=' '):
    rgx_chars = '|'.join(chars)
    #Removes the characters at the beginning of the string
    striped_left = re.sub('^[{}]*'.format(rgx_chars), '', string)
    #Removes the characters at the end of the string
    striped = re.sub('[{}]*$'.format(rgx_chars), '', striped_left)
    return striped

If you want to use search matching instead of substitutions, you can do :

def regexStrip(string, chars=' '):
    rgx_chars = '|'.join(chars)
    striped_search = re.search('[^{0}].*[^{0}]'.format(rgx_chars), string)
    if striped_search :
        return striped_search.group()
    else:
        return ''

Upvotes: 1

Related Questions