Find and extract a string of exactly "n" consecutive adjacent digits from an alphanumeric string

For an arbitrary alphanumeric string:

The quick brown 12345678901234 fox jumped over 987654321, on his second try.

can a regular expression retrieve a string of adjacent numbers that is exactly nine digits long if the string has more than nine digits?

That is, get 987654321and ignore 12345678901234?

The rule will be "get any nine-character string of digits that is either unlimited or limited to being limited to any character other than 0-9."

+4
source share
3 answers

This only matches your goal (no need to sit down with groups):

(?<!\d)\d{9}(?!\d)

Watch a live demo .

, " " . , , - .

, , -, / - 9- .

+3

:

\b\d{9}\b
# a word boundary (ie space, punctuation, comma)
# exactly nine consecutive digits
# another boundary

regex101.com.


:
\D(\d{9})\D
# not a digit
# nine consecutive digits
# not a digit

$1. , , . ( ). - \b.

0

Using \bto bind a string does not work for The quick brown 12345678901234 fox jumped over xx987654321xx, on his second try(limited to non-digits), which does:

(?:^|[^\d])(\d{9})(?:$|[^\d])

(not exciting groups to start / end or without numbers)

demo here

Edit: A simpler "modern" style:

(?:^|\D)(\d{9})(?:$|\D)

Python test (which captures several 9-digit groups):

import re
p=re.compile(r"(?:^|\D)(\d{9})(?:$|\D)")
print(re.findall(p,"The quick brown 12345678901234 fox jumped over 987654321dd, 123456789"))

gives:

['987654321', '123456789']
0
source

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


All Articles