I’m trying to create a regex expression to match any string that has exactly 9 digits. the digits can exist anywhere in the string.
For example, if you passed in the following strings, you’d get a match:
123456789
123aeiou456abc789
These strings would fail to provide a match
12345678
1234567890
Try this:
Or use this improved version. It assumes that you only want to match 0-9 and not other characters that represent digits in other languages. It also uses a non-capturing group to improve performance:
Here’s a breakdown of what it means:
^ Start of string. (?: Start a non-capturing group. [^0-9]* Match zero or more non-digits. [0-9] Match exactly one digit. ) Close the group. {9} Repeat the group exactly 9 times. [^0-9]* Match zero or more non-digits. $ End of string.Here’s a testbed for it:
Results: