VOOZH about

URL: https://www.geeksforgeeks.org/dsa/regular-expressions-to-validate-isbn-code/

⇱ Regular Expressions to Validate ISBN Code - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Regular Expressions to Validate ISBN Code

Last Updated : 23 Jul, 2025

Given some ISBN Codes, the task is to check if they are valid or not using regular expressions. Rules for the valid codes are:

  • It is a unique 10 or 13-digit.
  • It may or may not contain a hyphen.
  • It should not contain whitespaces and other special characters.
  • It does not allow alphabet letters.

Examples:

Input: str = ”978-1-45678-123-4?
Output: True

Input: str = ”ISBN446877428FCI?
Output: False
Explanation: It should contain digits and hyphens only.

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the number as written below:   
regex = "^(?=(?:[^0-9]*[0-9]){10}(?:(?:[^0-9]*[0-9]){3})?$)[\\d-]+$"

Where,

  • ^: Represents the beginning of the string.
  • ?: Either it contains or not.
  • $: Ending of the string.
  • *: Match preceding expression zero or more times
  • {n}: Match preceding expression exactly n times

Follow the below steps to implement the idea:

  • Create a regex expression for ISBN Codes.
  • Use Pattern class to compile the regex formed.
  • Use the matcher function to check whether the ISBN Code is valid or not.
  • If it is valid, return true. Otherwise, return false.

Below is the implementation of the above approach.


Output
true
true
true
false
false

Time Complexity: O(N) for each test case, where N is the length of the given string. 
Auxiliary Space: O(1)  

Related Articles:

Comment