Reputation: 1156
I need a regex to verify ISBN number entered by user.
ISBN must be a string contains only:
[10 or 13 digits] and hyphens
I tried ^[\d*\-]{10}|[\d*\-]{13}$
but it doesn't work.
My regex only matches: 978-1-5661
, 1-56619-90
, 1257561035
It should returns the results below:
"978-1-56619-909-4 2" => false
"978-1-56619-909-4" => true
"1-56619-909-3 " => false
"1-56619-909-3" => true
"isbn446877428ydh" => false
"55 65465 4513574" => false
"1257561035" => true
"1248752418865" => true
I really appreciate any help.
Upvotes: 4
Views: 16711
Reputation: 423
As mentioned at the accepted answer, not all 10 or 13 digit numbers are valid ISBN.
An ISBN consists of five groups of numbers that make out 13 digits. In 2007 the standard moved from 10 digits. The five groups can accept various lengths of numbers, which makes ISBN challenging to validate. Ref. https://en.wikipedia.org/wiki/International_Standard_Book_Number
One solution is this:
^(?:ISBN(?:-13)?:?\ )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$
Source: O'Reilly Regular Expressions Cookbook, 2nd edition
You may find many possible regexp for ISBN validation here: https://regexlib.com/Search.aspx?k=ISBN
Upvotes: 6
Reputation: 784958
You can use this regex with a positive lookahead:
^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$
(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)
is a positive lookahead that ensures we have 10 or 13 digits in the input.
Upvotes: 7