isbn regex in csharp

Here's a C# regular expression you can use to validate ISBNs:

main.cs
Regex regex = new Regex(@"^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$");
73 chars
2 lines

Here's an explanation of the regular expression:

  • ^: Matches the start of the string.
  • (?=: Positive lookahead assertion. Ensures that the following pattern matches the input, but doesn't consume any characters.
  • (?:\D*\d){10}: Matches any non-digit characters (\D*) followed by a digit (\d), exactly 10 times.
  • (?:(?:\D*\d){3})?$: Optionally matches any non-digit characters (\D*) followed by a digit (\d), exactly 3 times, at the end of the string (due to the $ anchor).
  • [\d-]+: Matches any digit or hyphen (-) character at least once.
  • $: Matches the end of the string.

You can use this regular expression with the Regex.IsMatch() method to check whether a string is a valid ISBN:

main.cs
string isbn = "978-3-16-148410-0";
if (Regex.IsMatch(isbn, @"^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$"))
{
    Console.WriteLine("Valid ISBN");
}
else
{
    Console.WriteLine("Invalid ISBN");
}
197 chars
10 lines

gistlibby LogSnag