Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
How to Validate MICR Code using Regular Expression?
Next article icon

Regular Expressions to Validate ISBN Code

Last Updated : 24 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Java




// Java program to validate the
// ISBN Code using Regular Expression
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the
    // ISBN Code
    public static boolean isValidISBNCode(String str)
    {
 
        // Regex to check valid ISBN Code
        String regex
            = "^(?=(?:[^0-9]*[0-9]){10}(?:(?:[^0-9]*[0-9]){3})?$)[\\d-]+$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the str
        // is empty return false
        if (str == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given
        // str using regular expression.
        Matcher m = p.matcher(str);
 
        // Return if the str
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "978-1-45678-123-4";
        System.out.println(isValidISBNCode(str1));
 
        // Test Case 2:
        String str2 = "1-56619-909-3";
        System.out.println(isValidISBNCode(str2));
 
        // Test Case 3:
        String str3 = "1207199818865";
        System.out.println(isValidISBNCode(str3));
 
        // Test Case 4:
        String str4 = "978-1-12345-909-4 2";
        System.out.println(isValidISBNCode(str4));
 
        // Test Case 5:
        String str5 = "ISBN446877428FCI";
        System.out.println(isValidISBNCode(str5));
    }
}
 
 

C++




// C++ program to validate the
// ISBN Code using Regular
// Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate the
// ISBN Code
bool isValidISBNCode(string str)
{
 
    // Regex to check valid
    // ISBN Code.
    const regex pattern("^(?=(?:[^0-9]*[0-9]){10}(?:(?:[^0-"
                        "9]*[0-9]){3})?$)[\\d-]+$");
 
    // If the str
    // is empty return false
    if (str.empty()) {
        return false;
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex_match(str, pattern)) {
        return true;
    }
    else {
        return false;
    }
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "978-1-45678-123-4";
    cout << isValidISBNCode(str1) << endl;
 
    // Test Case 2:
    string str2 = "1-56619-909-3";
    cout << isValidISBNCode(str2) << endl;
 
    // Test Case 3:
    string str3 = "1207199818865";
    cout << isValidISBNCode(str3) << endl;
 
    // Test Case 4:
    string str4 = "978-1-12345-909-4 2";
    cout << isValidISBNCode(str4) << endl;
 
    // Test Case 5:
    string str5 = "ISBN446877428FCI";
    cout << isValidISBNCode(str5) << endl;
 
    return 0;
}
 
 

Python3




# Python3 program to validate
# ISBN Code using Regular Expression
import re
 
# Function to validate
# ISBN Code
 
 
def isValidISBNCode(str):
 
    # Regex to check valid ISBN Code
    regex = "^(?=(?:[^0-9]*[0-9]){10}(?:(?:[^0-9]*[0-9]){3})?$)[\\d-]+$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver code
 
 
# Test Case 1:
str1 = "978-1-45678-123-4"
print(isValidISBNCode(str1))
 
# Test Case 2:
str2 = "1-56619-909-3"
print(isValidISBNCode(str2))
 
# Test Case 3:
str3 = "1207199818865"
print(isValidISBNCode(str3))
 
# Test Case 4:
str4 = "978-1-12345-909-4 2"
print(isValidISBNCode(str4))
 
# Test Case 5:
str5 = "ISBN446877428FCI"
print(isValidISBNCode(str5))
 
 

C#




// C# program to validate the
// ISBN Code
// using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG {
 
    // Main Method
    static void Main(string[] args)
    {
 
        // Input strings to Match
        // ISBN Code
        string[] str
            = { "978-1-45678-123-4", "1-56619-909-3",
                "1207199818865", "978-1-12345-909-4 2",
                "ISBN446877428FCI" };
        foreach(string s in str)
        {
            Console.WriteLine(isValidISBNCode(s) ? "true"
                                                 : "false");
        }
        Console.ReadKey();
    }
 
    // method containing the regex
    public static bool isValidISBNCode(string str)
    {
        string strRegex
            = @"^(?=(?:[^0-9]*[0-9]){10}(?:(?:[^0-9]*[0-9]){3})?$)[\d-]+$";
        Regex re = new Regex(strRegex);
        if (re.IsMatch(str))
            return (true);
        else
            return (false);
    }
}
 
 

Javascript




// Javascript program to validate
// ISBN Code using Regular Expression
 
// Function to validate the
// ISBN Code
function isValidISBNCode(str) {
    // Regex to check valid
    // ISBN CODE
    let regex = new RegExp(/^(?=(?:[^0-9]*[0-9]){10}(?:(?:[^0-9]*[0-9]){3})?$)[\d-]+$/);
 
    // if str
    // is empty return false
    if (str == null) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex.test(str) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "978-1-45678-123-4";
console.log(isValidISBNCode(str1));
 
// Test Case 2:
let str2 = "1-56619-909-3";
console.log(isValidISBNCode(str2));
 
// Test Case 3:
let str3 = "1207199818865";
console.log(isValidISBNCode(str3));
 
// Test Case 4:
let str4 = "978-1-12345-909-4 2";
console.log(isValidISBNCode(str4));
 
// Test Case 5:
let str5 = "ISBN446877428FCI";
console.log(isValidISBNCode(str5));
 
 
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:

  • Regular Expressions in Java
  • Python RegEx
  • JavaScript Regular Expressions


Next Article
How to Validate MICR Code using Regular Expression?
author
rahul_chauhan_1998
Improve
Article Tags :
  • DSA
  • Pattern Searching
  • Technical Scripter
  • regular-expression
  • Technical Scripter 2022
Practice Tags :
  • Pattern Searching

Similar Reads

  • How to validate IFSC Code using Regular Expression
    Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be
    8 min read
  • How to Validate MICR Code using Regular Expression?
    MICR stands for Magnetic Ink Character Recognition. This technology provides transaction security, ensuring the correctness of bank cheques. MICR code makes cheque processing faster and safer. MICR Technology reduces cheque-related fraudulent activities. Structure of a Magnetic Ink Character Recogni
    6 min read
  • How to validate ISIN using Regular Expressions
    ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
    6 min read
  • How to validate pin code of India using Regular Expression
    Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression. The valid pin code of India must satisfy the following conditions. It can be only six digits.It should not start with zero.First digit of the pin cod
    6 min read
  • Regular Expression to Validate a Bitcoin Address
    BITCOIN is a digital currency. During the digital currency transaction, a BTC address is required to verify the legality of a bitcoin wallet a Bitcoin address is a long set of alphanumeric characters that contains numbers and letters. A Bitcoin address indicates the source or destination of a Bitcoi
    6 min read
  • How to validate PAN Card number using Regular Expression
    Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters sh
    6 min read
  • How to validate CVV number using Regular Expression
    Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not ha
    5 min read
  • Validating UPI IDs using Regular Expressions
    Given some UPI IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid UPI ID: UPI ID is an alphanumeric String i.e., formed using digits(0-9), alphabets (A-Z and a-z), and other special characters.It must contain '@'.It should not contain whitespace.It may
    5 min read
  • How to validate MAC address using Regular Expression
    Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with
    6 min read
  • Validating Voter ID Card using Regular Expression
    Voter ID card is also known as EPIC (Electors Photo Identity Card). EPIC is an identification proof for Indian citizens over the age of 18.Given some Voter ids, the task is to check if they are valid or not using regular expressions. Rules for the valid VOTER ID: EPIC Number is a unique alphanumeric
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences