1

I am trying the following:

s = "Text text text [123] ['text']"

This is my function:

def getFromSquareBrackets(s):
    m = re.findall(r"\[([A-Za-z0-9_']+)\]", s)
    return m

But I am obtaining:

['123', "'text'"]

I want to obtain:

['123', 'text'] 

How can I ignore the single quotes?

FacundoGFlores
  • 7,388
  • 10
  • 57
  • 92

2 Answers2

3

You can make ' optional using ? as

>>> re.findall(r"\['?([^'\]]+)'?\]", s)
['123', 'text']

  • \['? Matches [ or ['.

  • ([^'\]]+) Matches anything other than ' or ] and captures them.

  • '?\] Matches ] or ']

nu11p01n73R
  • 25,677
  • 2
  • 36
  • 50
2

Make ' optional and outside the capturing group

m = re.findall(r"\['?([A-Za-z0-9_]+)'?\]", s)
Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178