Capturing all groups after a pattern

Viewed 51

I have something similar to this:

A: 1 2 3 4
B: 5 6 7 8
C: 9 10 11 12

I am interested in capturing the numbers in the B row. In other words, I want to match [' 5',' 6',' 7',' 8']. Bear in mind that I am not guaranteed that the number of rows or the amount of digits is like in my example.

The closest I got to is (?<=B:)( \d+)*, which matches:

enter image description here

What is the correct way of doing what I want strictly in Python regular expressions? Is it possible?

Edit: Some people rightly mentioned I could simply capture the row and then use split inside Python. This surely works, but the problem is that I am limited to using only a single regular expression.

1 Answers

Using the PyPi regex module that supports a quantifier in the lookbehind assertion:

(?<=B:[ \d]*)\d+

The pattern matches:

  • (?<= Positive lookbehind, assert what is to the left is
    • B:[ \d]* Match B: and optional spaces or digits
  • ) Close lookbehind
  • \d+ Match 1+ digits

See a regex demo or a Python demo.

import regex

pattern = r"(?<=B:[ \d]*)\d+"

s = ("A: 1 2 3 4\n"
     "B: 5 6 7 8\n"
     "C: 9 10 11 12")

print(regex.findall(pattern, s))

Output

['5', '6', '7', '8']

If you can not use the regex module, you can use a capture group and split:

import re

pattern = r"B: (\d+(?: \d+)*)"

s = ("A: 1 2 3 4\n"
     "B: 5 6 7 8\n"
     "C: 9 10 11 12")

res = re.search(pattern, s)
if res:
     print(res.group(1).split())

Output

['5', '6', '7', '8']
Related