0

I am trying to write a regex that grabs blocks of whitespace from either side of a string. I can get the beginning, but I can't seem to grab the end block.

s = '     This is a string with whitespace on either side     '

strip_regex = re.compile(r'(\s+)(.*)(something to grab end block)')
mo = strip_regex.findall(s)

What I get as an output is this:

[('        ', 'This is a string with whitespace on either side        ')]

I have played around with that to do at the end, and the best I can get is one whitespace but I can never just grab the string until the end of 'side'. I don't want to use the characters in side because I want the regex to work with any string surrounded by whitespace. I am pretty sure that it's because I am using the (.*) which is just grabbing everything after the first whitespace block. But can't figure out how to make it stop before the end whitespace block.

Thanks for any help :)

0

1 Answer 1

1

If what you want to do is strip whitespace, you could use strip() instead. See: https://www.journaldev.com/23625/python-trim-string-rstrip-lstrip-strip

As for your regex, if you want both the start and end whitespace, I suggest matching the whole line, with the middle part not greedy like so:

s = '     This is a string with whitespace on either side     '
strip_regex = re.compile(r'^(\s+)(.*?)(\s+)$')
mo = strip_regex.findall(s)

Result:

[('     ', 'This is a string with whitespace on either side', '     ')]

More about greedy: How can I write a regex which matches non greedy?

Sign up to request clarification or add additional context in comments.

1 Comment

That's awesome thank you! Literally just had to move the $ outside of the last group and it would have worked! I was trying to write a regex which would imitate the strip() function :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.