Regex get a certain size of digits and or with a symbol

1

People like to get the digits of size 9 , and whether or not they have an exclamation mark (!) at the end.

Example:

 blabla n123456789 bla bla 78 texto...
 987654321! texto qualquer 12 blaa
 123 bla blum 123741852 bobobl
 blablum 12345678901 papumpa...

Output:

 123456789
 987654321!
 123741852

In my Regex, the digit "cut" is greater than 9

 preg_match_all('/[!\d]{9,10}/', $a, $match);
 print_r($match);

Output:

 Array
 (
 [0] => Array
(
     [0] => 123456789
     [1] => 987654321!
     [2] => 123741852
     [3] => 1234567890 // <- FALHA
)

 )
    
asked by anonymous 16.02.2015 / 17:42

3 answers

0

this expression should serve

\d{9}

link

Update

to display the! together

\d{9}!?

-

One solution to this other is

\b\d{9}!?\b

link

    
16.02.2015 / 17:45
4

More complicated than it sounds!

To handle all possible cases I believe this is a correct regex:

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

It "says" roughly the following: "Give me all groups of 9 numbers that (be preceded by something that is not a number or that are the beginning of the string) AND (followed by an exclamation Or by something that is not a number or by the end of the string). ".

link contain the validation of the regex for your test case and for some other possible situations according to the description of the problem.

    
17.02.2015 / 05:33
1

The Adir solution is good, just a small detail, should be

\b\d{9}\b!?

to display yes or no!

    
17.02.2015 / 00:07