0

I am working on a RegEx in which I want any number of occurrences of white spaces and any number of occurrences of digits in the total length of 13. Something like

'           12'

or

'       115678'

Current Regex:

(^\s*\d[0-9]{1,12})$

How to get this variable occurrences using blocks

Tom Lord
  • 27,404
  • 4
  • 50
  • 77

3 Answers3

0

You can allow upto 13 spaces and/or numbers with a character class:

^[\t \d]{1,13}$

If white spaces also includes new lines use the \s meta character in place of the space and \t.

^[\s\d]{1,13}$

If this is PHP you can use \h for horizontal whitespaces, Javascript doesn't support that.

^[\h\d]{1,13}$

A demo (of version 2): https://regex101.com/r/gZ9rA8/1

Non regex PHP version:

$string = '       115678';
if(strlen($string) <=13 && is_numeric($string)) {
    echo 'It\'s GOOD!';
}

https://eval.in/639391

Non regex javascript:

var string = '       111578';
if(string.length <= 13 && !isNaN(string.trim())) {
     alert('good');
} else {
    alert('bad')
}

Demo: https://jsfiddle.net/h9mx0tmn/

chris85
  • 23,846
  • 7
  • 34
  • 51
0

Since there are two conditions to be met:-

  1. any occurrences of white spaces followed by any occurrences of digits
  2. total length of 13

Use positive look ahead regex like this:-

/(?=^\s*\d*$)(^.{13}$)/

Visit here for more about positive look ahead regex:-

Regex lookahead, lookbehind and atomic groups

Hope this helps.

Community
  • 1
  • 1
Capital C
  • 319
  • 3
  • 13
-1

You could do with one huge ugly and inefficient regular expression:

^\s{0}\d{13}|\s{1}\d{12}|\s{2}\d{11}|\s{3}\d{10}|\s{4}\d{9}|\s{5}\d{8}|\s{6}\d{7}|\s{7}\d{6}|\s{8}\d{5}|\s{9}\d{4}|\s{10}\d{3}|\s{11}\d{2}|\s{12}\d{1}$

I would recommend against doing it this way though. Instead, you should do something like that: check the string against the regular expression ^\s{0,13}\d{0,13}$ and then verify that its length is 13 in a separate step.

redneb
  • 21,794
  • 6
  • 42
  • 54