Given some words of Gender, the task is to check if they are valid or not using regular expressions. The correct responses can be as given below:
- Male / male / MALE / M / m
- Female / female / FEMALE / F / f
- Not prefer to say
Example:
Input: M
Output: TrueInput: S
Output: False
Approach: The problem can be solved based on the following idea:
Create a regex pattern to validate the number as written below:
regex= “(?:m|M|male|Male|f|F|female|Female|FEMALE|MALE|Not prefer to say)$”
Just check whether any of the words are present in regex or not using (?:)
Follow the below steps to implement the idea:
- Create a regular expression for Gender.
- If the Input string is empty, return False.
- Else, Use the Pattern class to compile the regex formed.
- Use the matcher function to check whether the Gender Is valid or not.
- If it is valid, return true. Otherwise, return false.
Below is the Implementation of the above approach:
C++
|
Java
|
Python3
|
Javascript
|
true true true true true false true
Related Articles: