### Regex for validation of 9 numbers with single space

84 观看

2回复

6 作者的声誉

I need a regex for validating a 9digit number with a single space in-between

So far I have tried

``````^([0-9]{0-9})\s{1}\$
``````

3

14596 作者的声誉

## Code

See regex in use here

``````^(?=\d+ \d+\$)[\d ]{10}\$
``````

## Results

### Input

``````1 23456789
12 3456789
123 456789
1234 56789
12345 6789
123456 789
1234567 89
12345678 9

123456789
123456789
123456789
1 2 3456789
1 234567890
``````

### Output

Only matches are below.

``````1 23456789
12 3456789
123 456789
1234 56789
12345 6789
123456 789
1234567 89
12345678 9
``````

## Explanation

• `^` Assert position at the start of the line
• `(?=\d+ \d+\$)` Positive lookahead ensuring what follows matches the following
• `\d+` Match one or more digits
• Match a literal space
• `\d+` Match one or more digits
• `\$` Assert position at the end of the line
• `[\d ]{10}` Match any digit or space character exactly 10 times
• `\$` Assert position at the end of the line

1

96253 作者的声誉

Don't use regex.

1. Check the length is 10.
2. Count the numbers and spaces:

``````int nSpaces = 0, nNumbers = 0;
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c == ' ') nSpaces++;
else if (c >= '0' && c <= '9') nNumbers++;
}
``````
3. Check that there are 9 numbers and 1 space.

``````if (nSpaces == 1 && nNumbers == 9) { ... }
``````