The regex that I'm trying to implement should match the following data:
123456
12345
23456
5
1
2
2345
It should not match the following:
12 456
1234 6
1 6
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*
?= 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).
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] ).
You can match a space character with just the space character; [^ ] matches anything but a space character.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With