Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex: contains at least 8 decimal digits

Tags:

regex

I need regex to check if a string contains 8 decimal digits or more. It can contain anything else and the digits don't have to be consecutive.

Thanks in advance

EDIT: replaced "number" by "decimal digit" to match accepted answer.

like image 597
Alistair Avatar asked Mar 24 '11 07:03

Alistair


People also ask

What is the regex for decimal number?

A better regex would be /^\d*\.?\ d+$/ which would force a digit after a decimal point. @Chandranshu and it matches an empty string, which your change would also solve.

What does \d mean in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

How does regex Match 5 digits?

match(/(\d{5})/g);

Why * is used in regex?

* - means "0 or more instances of the preceding regex token"


2 Answers

/([^\d]*\d){8}/

Perhaps not the most elegant / efficient way to do it, but it works. Basically it will match eight decimals (optionally, with non-decimals between them). If there are more than eight, it will match too.

EDIT
As @Tomalak has pointed out, [^\d] equals \D by definition:

/(\D*\d){8}/
like image 192
jensgram Avatar answered Dec 19 '22 05:12

jensgram


A tweak to allow the last character to be non-numeric:

/(\D*\d){8,}\D*/
like image 42
chaserino Avatar answered Dec 19 '22 06:12

chaserino