Reputation: 91
How I can write a regex which accepts 10 or 14 digits separated by a single space in groups of 1,2 or 3 digits?
examples:
123 45 6 789 1 is valid
1234 567 8 9 1 is not valid
(group of 4 digits)
123 45 6 789 109 123 8374 is not valid
(not 10 or 14 digits)
EDIT This is what I have tried so far
[0-9 ]{10,14}+
But it validates also 11,12,13 numbers, and doesn't check for group of numbers
Upvotes: 1
Views: 219
Reputation: 168
aggtr,
You can match your use case with the following:
^(?:\d\s?){10}$|^(?:\d\s?){14}$
^ means the beginning of the string and $ means the end of the string. (?:...) means a non-capturing group. Thus, the part before the | means a string that starts and has a non-capturing group of a decimal followed by an optional space that has exactly 10 items followed by the end of the string. By putting the | you allow for either 10 or 14 of your pattern.
Edit I missed the part of your requirement to have the digits grouped by 1, 2, or 3 digits.
Upvotes: 0
Reputation: 785581
You may use this regex with lookahead assertion:
^(?=(?:\d ?){10}(?:(?:\d ?){4})?$)\d{1,3}(?: \d{1,3})+$
(?=...)
is lookahead assertion that enforces presence of 10 or 14 digits in input.\d{1,3}(?: \d{1,3})+
matches input with 1 to 3 digits separated by space with no space allowed at start or end.Upvotes: 2