Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a selection of digits only if preceded by a minimum of x digits

Tags:

python

regex

Say I have a number: 6278041121932517

If I want to get 11219325

I have a regex of:

re.search(r"((1|2)\d{7})", "6278041121932517")

but the thing is, it might begin with a 1 or a 2. So I want to add a minimum buffer beforehand say, 4 digits. I thought about look-behind, but it doesn't support n lengths.

like image 841
A. L Avatar asked Feb 06 '23 02:02

A. L


2 Answers

It seems you may use

^\d{4,}?([12]\d{7})

See the regex demo

Details:

  • ^ - start of string
  • \d{4,}? - 4 or more digits, but as few as possible
  • ([12]\d{7}) - Group 1 (your value):
    • [12] - 1 or 2
    • \d{7} - 7 digits

See Python demo:

import re
m = re.search(r"^\d{4,}?([12]\d{7})", "6278041121932517")
if m:
    print(m.group(1))
# => 11219325
like image 181
Wiktor Stribiżew Avatar answered Feb 08 '23 14:02

Wiktor Stribiżew


If all you want is a "buffer," you don't even need to change the regex for that. Just slice off a few characters.

>>> import re
>>> re.search(r"((1|2)\d{7})", "6278041121932517").group()
'27804112'
>>> re.search(r"((1|2)\d{7})", "6278041121932517"[4:]).group()
'11219325'
like image 35
TigerhawkT3 Avatar answered Feb 08 '23 14:02

TigerhawkT3