regex to capture group if group is before or after a specific string

Viewed 1054

i want to grab a number if the number is before or after a certain text ("b"), using python and a single regex. The "single" here is important....

so the following case should match (even if the first is optional as will never happen...)

  • b 1 b
  • b 2 c
  • c 3 b

this should not:

  • c 4 d

i toyed around (lookahead and back) but nothing really worked. i belive this should be possible using some look around stuff and ... magic? But i can't figure out how...

see this regex101 for a starting point...

if this is not possible, why? if this is possible, how?

2 Answers

Using the example you have given, the following pattern will match any number (group of one or more consecutive numerical digits) preceded by b or followed by b.

(?<=b\s)\d+|\d+(?=\sb)

First clause (?<=b\s)\d+

Look-back to check for b and match one or more following numerical digits

or |

Conditional telling engine to check second clause if first does not produce match.

Second clause \d+(?=\sb)

Match one or more numerical digits only if followed by b as defined by look-ahead.

I suggest using two regex matchers, one to capture the number if it before the text ("b"), and one to do so if it is after the text.

To match numbers before text 'b'

/([0-9]+)b/g

To match numbers after text 'b'

/b([0-9]+)/g
Related