Regular Expressions to Validate ISBN Code
source link: https://www.geeksforgeeks.org/regular-expressions-to-validate-isbn-code/?utm_campaign=newhomepage
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Regular Expressions to Validate ISBN Code
- Last Updated : 15 Dec, 2022
Given some ISBN Codes, the task is to check if they are valid or not using regular expressions. Rules for the valid codesare:
- 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: TrueInput: 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.
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 Codes is valid or not.
- If it is valid, return true. Otherwise, return false.
Below is the implementation of the above approach.
- Python3
- Javascript
// 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)); } }
true true true false false
Related Articles:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK