-1

I have a sample string as - x = "something [TextA][TextB]", with following re command-

re.search('\[(.*)\]',x).groups() 

I was able to achieve outcome as - "[TextA][TextB]" but I am looking for outcome as list as - ["[TextA]","[TextB]"]

NaN
  • 1,012
  • 3
  • 13
  • 25

1 Answers1

0

I was able to achieve outcome as - "[TextA][TextB]"

Because .* is greedy, the first match skips past the first ] enclosing TextA and continues to the second one enclosing TextB.

Use .*? for a non-greedy match. You don't strictly need this tool; you can instead match "any number of characters that are not ]", like [^\]]*. But I think .*? is a lot easier, and generalizes better.

but I am looking for outcome as list

If you need to get a specific number of matches, then you can explicitly specify each in your regex, with the appropriate capture for each. If you need any number of matches, use findall rather than search:

>>> re.findall('\[(.*?)\]', 'foo[bar][baz]')
['bar', 'baz']
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153