I have a regex with certain conditions
- Only allow digits and some characters ie space . ( - ) x X
- Total digits excluding the characters must be between 8 to 20
I have the first condition, 2nd seems bit tricky for me
^[ \d\s\-\.\(\)xX]{8,20}$
Thank you for your time.
CodePudding user response:
^[ \.\ \(\-\)xX]*(?:\d[ \.\ \(\-\)xX]*){8,20}$
[ \.\ \(\-\)xX]*
matches any number of the nonnumeric characters you've listed. We start by doing this at the beginning of the string. (This part can be removed if the string is not allowed to start with one of those characters.)- We then match 8-20 digits, each of which can be followed by any number of said nonnumeric characters.
CodePudding user response:
The 8 to 20 digits requirement is a bit ugly, but we can handle that using positive and negative lookaheads. Consider this version:
^(?=(?:\D*\d){8})(?!(?:\D*\d){21})[\d\s.()xX -] $
Explanation:
^
from the start of the input(?=(?:\D*\d){8})
assert that 8 or digits appear(?!(?:\D*\d){21})
but assert that more than 20 digits do NOT appears[\d\s.()xX -]
match numbers, whitespace, (), , x, X or - 1 or more times$
end of the input