I want a python regex to capture either a bracket or an empty string. Trying the usual approach is not working. I need to escape something somewhere but I've tried everything I know.
one = "this is the first string [with brackets]"
two = "this is the second string without brackets"
# This captures the bracket on the first but throws
# an exception on the second because no group(1) was captured
re.search('(\[)', one).group(1)
re.search('(\[)', two).group(1)
# Adding a "?" for match zero or one occurrence ends up capturing an
# empty string on both
re.search('(\[?)', one).group(1)
re.search('(\[?)', two).group(1)
# Also tried this but same behavior
re.search('([[])', one).group(1)
re.search('([[])', two).group(1)
# This one replicates the first solution's behavior
re.search("(\[+?)", one).group(1) # captures the bracket
re.search("(\[+?)", two).group(1) # throws exception
Is the only solution for me to check that the search returned None?
The answer is simple! :
(\[+|$)
Because the only empty string you need to capture is the last of the string.
Here's a different approach.
import re
def ismatch(match):
return '' if match is None else match.group()
one = 'this is the first string [with brackets]'
two = 'this is the second string without brackets'
ismatch(re.search('\[', one)) # Returns the bracket '['
ismatch(re.search('\[', two)) # Returns empty string ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With