Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need regex to match 1 or more of exactly n-digit numbers

Tags:

regex

I need a regex to match a series of one or more n-digit numbers, separated by comma, ie:

abc12345def returns 12345
abc12345,23456def returns 12345,23456

so far I got this: \d{5}(,\d{5})*

problem is it also matches in cases like these:

123456 returns 12345, but I need it not to match if the number is longer than 5. So I need numbers of exactly 5 digits, and if a number is shorter or longer it's a no-match

Thanks

like image 208
Lukasz Avatar asked Feb 18 '11 17:02

Lukasz


People also ask

How does regex Match 5 digits?

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

How do you match a number range in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

Which regex matches one or more digits Python?

You can use out\dmf\d+ , or, if you want to match only 1 or 2 digits at the end, out\dmf\d{1,2} .


2 Answers

Which language are you using for your regexes? You want to put non-digit markers around your \d{5}'s; here is the Perl syntax (with a negative look-ahead/look-behind fix by Lukasz):

(?<![\d,])\d{5}(,\d{5})*(?![\d,])
like image 120
Jeremiah Willcock Avatar answered Sep 18 '22 22:09

Jeremiah Willcock


Actually I think I got it! (?<!\d)\d{5}(?!\d)(,(?<!\d)\d{5}(?!\d))*

I used the look-ahead and look-behind

Thanks.

like image 39
Lukasz Avatar answered Sep 21 '22 22:09

Lukasz