Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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* 
like image 448
Loren Avatar asked Apr 06 '16 06:04

Loren


People also ask

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

What does \d mean in regex?

In regex, the uppercase metacharacter is always the inverse of the lowercase counterpart. \d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).

How do I match a character except space in regex?

You can match a space character with just the space character; [^ ] matches anything but a space character.


2 Answers

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.

like image 29
heemayl Avatar answered Sep 18 '22 13:09

heemayl


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.

like image 196
Wiktor Stribiżew Avatar answered Sep 21 '22 13:09

Wiktor Stribiżew