3

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')]]
4
  • 1
    You need more ?:, then. Commented Aug 17, 2021 at 21:20
  • 2
    I note that your regex starts with '((:(?:. Did you mean for that to be '((?:(?:? Commented Aug 17, 2021 at 21:20
  • 1
    Re-write to use only as many capturing groups as you need, (\w+(?:\s+\w+)*)\[([+-]\d)] Commented Aug 17, 2021 at 21:22
  • 1
    Wiktor your solution was what was needed (along with the others who noted the same thing), if you post it as an answer I will select it as the solution - thanks!! Also how did you know it was more ? and not less ? Commented Aug 17, 2021 at 21:29

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.