Avoiding an always-empty regex group with re.findall

Viewed 74

I have a list of string lists, and am looping through each list to search for a regex pattern, which is using regex groups and produces 3 groups, so the output is in a tuple of 3, as shown below:

regex = '((:(?:\w+\s)+)?\w+)\[((?:\+|\-)\d)\]'


matches = []

for line in sentences:

    result = re.findall(regex, str(line))
    matches.append(result)

Producing the following output:

[[('very good', '', '+3'), ('good', '', '+2')]]

However, I do not want the middle group to be output in the list, as you can see, it is always empty, how do I modify the regex pattern or modify what I am using to make sure only 'very good' and '+3' (for example in the first match) appear as the tuple ('very good', '+3') and NOT the middle blank tuple?

I.e. I want my output to be:

[[('very good', '+3'), ('good', '+2')]]
1 Answers

You need to revamp the pattern to match and capture only what is necessary:

(\w+(?:\s+\w+)*)\[([+-]\d)]

See the regex demo.

Details:

  • (\w+(?:\s+\w+)*) - Group 1: one or more word chars and then zero or more occurrences of one or more whitespaces and one or more word chars
  • \[ - a [ char
  • ([+-]\d) - Group 2: + or - and then a digit
  • ] - a ] char.
Related