问题
I a looking for a Regex to match a string which should:
- start with a digit
- 'in-between' have a permutation of exactly 7 digits and 2 hyphens, without 2 consecutive hyphens
- end with a sequence of digit, hyphen, digit
Match:
- 01-234-5678-9
- 01234-56-78-9
- 0123-4-5678-9
- 012-345-678-9
- 01-234567-8-9
- 01-234-5678-9
- 0-12345-678-9
- 0-123-45678-9
- 0-123-45678-9
- 01-23456-78-9
- 0-123456-78-9
- 0-1234567-8-9
No Match:
- 01-234-56789-0
- 01-234-567-8
- 01--2345678-9
- 01-2345678--9
- 0-1-23456789
- -01-2345678-9
For now, I could not quite figure out how to match the 2 'in-between' hyphens: ^\d\d{7}\d-\d$
EDIT: Thanks to the answers I had to this question, I was able to expand it to this other question regarding ISBN-10 and ISBN-13...
回答1:
My two cents:
^(?=.{11}-\d$)(?:\d+-){3}\d
See the online demo
^- Start string anchor.(?=- Open positive lookahead:.{11}-\d$- Any character other than newline 11 times followed by a hypen, a single digit and the end string anchor.)- Close positive lookahead.
(?:- Open non-capture group:\d+-- 1+ digit followed by an hyphen.){3}- Close non-capture group and match three times.
\d- Match a single digit.
I guess alternatively even ^(?=.{13}$)(?:\d+-){3}\d$ would work.
回答2:
You can assert 7 digits and the digit - digit part at the end.
For the match there should be at least a single digit before and after the hyphen to prevent consecutive hyphens.
^\d(?=(?:-?\d){7}-?\d-\d$)\d*-\d+-\d*\d-\d$
^Start of string\dMatch a single digit(?=Positive lookahead(?:-?\d){7}Match 7 digits separated by an optional--?\d-\d$Match an optional-and the\d-\d$at the end
)Close the lookahead\d*-\d+-\d*\d-\dMatch possible formats where all hyphens are separated by at least a single digit$End of string
Regex demo
来源:https://stackoverflow.com/questions/65922591/regex-for-a-permutation-of-exactly-7-digits-and-2-hyphens-without-2-consecutive