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,858
  • 12
  • 64
  • 94

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
  • 26,397
  • 3
  • 39
  • 52
2

Make ' optional and outside the capturing group

m = re.findall(r"\['?([A-Za-z0-9_]+)'?\]", s)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188