I've tried the following regex, but 开发者_JAVA百科it appears that nested "[]" are not allowed.
[\d[\s-]*]{9-23}
You're on the right track, what you're looking for is probably:
(\d[\s-]*){8,22}\d
- a digit
- followed by any number of whitespace/dash
- 8-22 times
- followed by the final digit
It appears that you don't want to match leading or trailing spaces and dashes, so the pattern that I think will work is:
^\d([- ]*\d){8,22}$
That is: one digit, followed by between 8 and 22 groups of zero or more dashes or spaces followed by a single digit.
Another solution which might be more obvious is this two-step solution:
- match against \d[-\d ]+\d to make sure you have a string of digits, spaces and dashes which both begins and ends with at least one digit
- strip out just the digits and count how many you have
Let's try this:
([0-9][ -]*){9,23}
This regular expression is too short of an answer so here's my favorite
For what it's worth, you might consider splitting it into two steps. In C#, for example, you could do something like this.
Regex.Match(Regex.Replace(str, "[ -]", ""), @"^\d{9,23}")
This is two string operations, so of course there may be a performance penalty if that matters to you. But it may be more readable for the next guy.
精彩评论