-1

Is there a simple way to ignore whitespace between digits within a regular expression?

I want a RegEx to match on any 10 digit number, including numbers with spaces between them.

For example, the following 3 examples would match:

  1. 4874526395
  2. 4874 526 395
  3. 48745 26395

^\d{10}$ is the current regular expression, and expecting I'll need to use \s somewhere but unsure how.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

5 Answers5

2

You can use ^( *\d){10} *$ to match 10 digits with space characters before/after or in-between them.

diagram of regex that allows spaces around
Regexper

If you only want to allow spaces in-between, but not before/after, you can use ^\d( *\d){9}$ instead.

diagram of regex that doesn't allow spaces around
Regexper

Probably better understandable would be to remove space characters first.

string.replace(/ +/g, "").match(/^\d{10}$/)

If you want to match all whitespace (space, newline, tab, etc.), not just spaces, you can replace the space in the regex with \s.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
1

You can use the following regular expression:

^(\d\s*){9}\d$

Note that this does not match with leading or trailing whitespace. If you need to match those cases too, simply add a \s* before and after the regular expression (so ^\s*(\d\s*){9}\d\s*$).

You can check this regexp interactively at regex101 and generate code there, if needed.

miile7
  • 2,547
  • 3
  • 23
  • 38
0

I might be inclined to just strip off whitespace before checking the input for the correct number of digits:

var input = "4874 526 395";
if (/^\d{10}$/.test(input.replace(/\s+/g, ""))) {
    console.log("MATCH");
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

With following code you can remove gap between numbers even you have string between them

String repl = "111 222 333".replaceAll("(?<=\d) +(?=\d)", ""); //=> Hello 111222333 World!

This regex "(?<=\d) +(?=\d)" makes sure to match space that are preceded and followed by a digit.

0

There is a proposed way how to do so here: How to ignore whitespace in a regular expression subject string?

But in this case it will be easier just to replace all whitespaces with empty string and use your regex:

s.replaceAll("\\s+","").matches("^\\d{10}$")
xyz
  • 812
  • 9
  • 18