Regex pick certain digit size and or symbol

Asked

Viewed 1,072 times

1

Personal how to pick up the digits of size 9, and whether or not there is 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...

Exit:

 123456789
 987654321!
 123741852

In my Regex, bring "cut" digits higher than 9

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

Exit:

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

 )

3 answers

4

More complicated than it looks !

To deal with all possible cases I believe that this is a correct regex:

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

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

https://regex101.com/r/hC8cN6/2 contain the regex validation for your test case and for some other possible situations according to the problem description.

  • Very good did not know these regex, more thing to study =D

1

Adir’s solution is good, just one small detail, should be

\b\d{9}\b!?

to display yes or no !

0


  • What about the exclamation mark (!) ?

  • you want to display it too?

  • yes I want @Adirkuhn

  • Cool @Adirkuhn, to be perfect just skip the digits above 9. In the example above in the last line that contains 11 digits it cuts

  • Thank you @Adirkuhn

Browser other questions tagged

You are not signed in. Login or sign up in order to post.