Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match zero or more brackets in python regex

Tags:

python

regex

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?

like image 892
thomashollier Avatar asked May 08 '14 23:05

thomashollier


2 Answers

The answer is simple! :

(\[+|$)

Because the only empty string you need to capture is the last of the string.

like image 86
Casimir et Hippolyte Avatar answered Sep 21 '22 17:09

Casimir et Hippolyte


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  ''
like image 22
hwnd Avatar answered Sep 24 '22 17:09

hwnd