4.13. Validate ISBNs
Problem
You need to check the validity of an International Standard Book Number (ISBN), which can be in either the older ISBN-10 or the current ISBN-13 format. You want to allow a leading “ISBN” identifier, and ISBN parts can optionally be separated by hyphens or spaces. All of the following are examples of valid input:
ISBN 978-0-596-52068-7ISBN-13: 978-0-596-52068-7978 0 596 52068 79780596520687ISBN-10 0-596-52068-90-596-52068-9
Solution
You cannot validate an ISBN using a regex alone, because the last digit is computed using a checksum algorithm. The regular expressions in this section validate the format of an ISBN, whereas the subsequent code examples include a validity check for the final digit.
Regular expressions
Three regex solutions follow that allow you to match ISBN-10s and ISBN-13s, either exclusively or together. Each of the solutions is shown with and without free-spacing and comments. JavaScript doesn’t support free-spacing, but with other programming languages you can choose whichever suits you best.
In the free-spaced regexes, literal space characters have been escaped with backslashes. Java’s free-spacing mode requires that even spaces within character classes be escaped.
ISBN-10:
^(?:ISBN(?:-10)?:?●)?(?=[0-9X]{10}$|(?=(?:[0-9]+[-●]){3})[-●0-9X]{13}$)↵ [0-9]{1,5}[-●]?[0-9]+[-●]?[0-9]+[-●]?[0-9X]$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
^ (?:ISBN(?:-10)?:?\ )? # Optional ISBN/ISBN-10 identifier. (?= # Basic format ...