Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for matching 9-23 digits with any number of spaces or dashes inbetween

Tags:

regex

I've tried the following regex, but it appears that nested "[]" are not allowed.

[\d[\s-]*]{9-23}

like image 690
Trent Whiteley Avatar asked Mar 28 '11 18:03

Trent Whiteley


People also ask

How do I match a range of numbers in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.

How do you use spaces in regex?

Find Whitespace Using Regular Expressions in Java The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

You're on the right track, what you're looking for is probably:

(\d[\s-]*){8,22}\d
  • a digit
  • followed by any number of whitespace/dash
  • 8-22 times
  • followed by the final digit
like image 159
Martin Avatar answered Oct 03 '22 06:10

Martin


It appears that you don't want to match leading or trailing spaces and dashes, so the pattern that I think will work is:

^\d([- ]*\d){8,22}$

That is: one digit, followed by between 8 and 22 groups of zero or more dashes or spaces followed by a single digit.

Another solution which might be more obvious is this two-step solution:

  1. match against \d[-\d ]+\d to make sure you have a string of digits, spaces and dashes which both begins and ends with at least one digit
  2. strip out just the digits and count how many you have
like image 34
Bryan Oakley Avatar answered Oct 03 '22 07:10

Bryan Oakley