user8498295
user8498295

Reputation:

Regex Version of Strip(): Using Function Parameter Directly in Regex Compile

I am working on the 'Regex Version of Strip()' practice problem from Automate the Boring Stuff, Chapter 7. I have seen the use of '+char+' to pull a function parameter directly into the regex compile, but I do not understand how this formatting works.

def pseudoStrip(inputString, char='\s'):
    stripRegex = re.compile(r'^'+char+'|'+char+'+$')
    print(stripRegex.sub('', inputString))

Is '+char+' the same as ['+char+']?

Is there a more readable or Pythonic way of performing this task?

Upvotes: 0

Views: 418

Answers (2)

alexstacksbruh
alexstacksbruh

Reputation: 11

This is probably the least Pythonic way of doing this problem, but it only uses stuff that's been taught in the book up to this point. It works with all characters except \ (backslash).

import re

def regexStrip(string,characters):
    mo = spaceStripRegex.search(string) # Calls upon the global regex for separating left and right white space from content
    string = mo.group(2)    # Isolates the string content from bounding white space and re-assigns it to a variable
    
    characters = '[' + characters + ']' # Stores other characters to be stripped in format compatible with character class
    
    # Regex for stripping other characters contains argument built via string concatenation as opposed to single raw string
    characterStripRegex = re.compile(
        '^' + characters + '*' +    # Zero or more of the characters to be stripped on left side of content
        r'(.*?)' +  # Defines unstripped content as the only group. Nongreedy so as not to include characters to be stripped on right side 
        characters + '*$')  # Zero or more of the characters to be stripped on the right side of the content
    mo = characterStripRegex.search(string)
    string = mo.group(1)
    print(string)
    
# Global regex that groups initial string into left white space, content, and right white space
spaceStripRegex = re.compile(r'''
    ^(\s)*  # Left white space if any
    (.*?)   # String content
    (\s)*$  # Right white space if any
    ''', re.VERBOSE)

string = '  **SpamSpamBaconSpamEggsSpamSpam   '
characters = 'ampS*'

regexStrip(string,characters)

Upvotes: 0

Bharat Mahindra
Bharat Mahindra

Reputation: 1

Throw your regex here and it will tell you what the expression does: https://regex101.com/#python

Upvotes: 0

Related Questions