![]() |
VOOZH | about |
Given some ISBN Codes, the task is to check if they are valid or not using regular expressions. Rules for the valid codes are:
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.
- *: Match preceding expression zero or more times
- {n}: Match preceding expression exactly n times
Follow the below steps to implement the idea:
Below is the implementation of the above approach.
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: