Loren
Loren

Reputation: 1310

Regex that will match 6 characters that only allows digits, leading, and trailing spaces

The regex that I'm trying to implement should match the following data:

  1. 123456
  2. 12345 
  3.  23456
  4.      5
  5. 1     
  6.       
  7.   2   
  8.  2345 

It should not match the following:

  1. 12 456
  2. 1234 6
  3.  1 6
  4. 1 6

It should be 6 characters in total including the digits, leading, and trailing spaces. It could also be 6 characters of just spaces. If digits are used, there should be no space between them.

I have tried the following expressions to no avail:

^\s*[0-9]{6}$
\s*[0-9]\s*

Upvotes: 30

Views: 5748

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626896

You can just use a *\d* * pattern with a restrictive (?=.{6}$) lookahead:

^(?=.{6}$) *\d* *$

See the regex demo

Explanation:

  • ^ - start of string
  • (?=.{6}$) - the string should only have 6 any characters other than a newline
  • * - 0+ regular spaces (NOTE to match horizontal space - use [^\S\r\n])
  • \d* - 0+ digits
  • * - 0+ regular spaces
  • $ - end of string.

Java demo (last 4 are the test cases that should fail):

List<String> strs = Arrays.asList("123456", "12345 ", " 23456", "     5", // good
"1     ", "      ", "  2   ", " 2345 ",  // good
"12 456", "1234 6", " 1   6", "1    6"); // bad
for (String str : strs)
    System.out.println(str.matches("(?=.{6}$) *\\d* *"));

Note that when used in String#matches(), you do not need the intial ^ and final $ anchors as the method requires a full string match by anchoring the pattern by default.

Upvotes: 42

heemayl
heemayl

Reputation: 42017

You can also do:

^(?!.*?\d +\d)[ \d]{6}$
  • The zero width negative lookahead (?!.*?\d +\d) ensures that the lines having space(s) in between digits are not selected

  • [ \d]{6} matches the desired lines that have six characters having just space and/or digits.

Upvotes: 7

Related Questions