Chapter 7, Automate the boring stuff with Python, practice project: regex version of strip()
Question: I am reading the book "Automate the boring stuff with Python'. In Chapter 7,
in the project practice: the regex version of strip(), here is my code (I use
Python 3.x):

    
    
    def stripRegex(x,string):
    import re
    if x == '':
        spaceLeft = re.compile(r'^\s+')
        stringLeft = spaceLeft.sub('',string)
        spaceRight = re.compile(r'\s+$')
        stringRight = spaceRight.sub('',string)
        stringBoth = spaceRight.sub('',stringLeft)
        print(stringLeft)
        print(stringRight)
    
    else:
        charLeft = re.compile(r'^(%s)+'%x)
        stringLeft = charLeft.sub('',string)
        charRight = re.compile(r'(%s)+$'%x)
        stringBoth = charRight.sub('',stringLeft)
    print(stringBoth)
    
    x1 = ''
    x2 = 'Spam'
    x3 = 'pSam'
    string1 = '      Hello world!!!   '
    string2 = 'SpamSpamBaconSpamEggsSpamSpam'
    stripRegex(x1,string1)
    stripRegex(x2,string2)
    stripRegex(x3,string2)
    

And here is the output:

    
    
    Hello world!!!   
          Hello world!!!
    Hello world!!!
    BaconSpamEggs
    SpamSpamBaconSpamEggsSpamSpam
    

So, my regex version of strip() nearly work as the original version. In the
origninal version, the output always is "BaconSpamEggs" no matter you passed
in 'Spam', 'pSam', 'mapS', 'Smpa'... So how to fix this in Regex version???


Answer: You could check for multiple characters in the regex like this:

    
    
    charLeft = re.compile(r'^([%s]+)' % 'abc') 
    print charLeft.sub('',"aaabcfdsfsabca")
    >>> fdsfsabca
    

Or even better, do it in a single regex:

    
    
    def strip_custom(x=" ", text):
        return re.search(' *[{s}]*(.*?)[{s}]* *$'.format(s=x), text).group(1)
    
    split_custom('abc', ' aaabtestbcaa ')
    >>> test
    

