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

Let's say I have a number: 6278041121932517

If I want to get 11219325

I have a regex:

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

but the fact is that it can start with 1 or 2. Therefore, I want to add a minimum buffer in advance, say 4 digits. I was thinking about look-behind, but it does not support n lengths.

+4
source share
2 answers

It seems you can use

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

Watch the regex demo

More details

  • ^ - beginning of line
  • \d{4,}? - 4 or more digits, but as small as possible
  • ([12]\d{7}) - Group 1 (your value):
    • [12]- 1or2
    • \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
+5
source

, , "", . .

>>> import re
>>> re.search(r"((1|2)\d{7})", "6278041121932517").group()
'27804112'
>>> re.search(r"((1|2)\d{7})", "6278041121932517"[4:]).group()
'11219325'
+3

Source: https://habr.com/ru/post/1669999/


All Articles