Python program to verify that a string only contains letters, numbers, underscores and dashes
Given a string, we have to find whether the string contains any letters, numbers, underscores, and dashes or not. It is usually used for verifying username and password validity. For example, the user has a string for the username of a person and the user doesn’t want the username to have any special characters such as @, $, etc.
Prerequisite: Regular Expression in Python
Let’s see the different methods for solving this task:
Method 1: Using Regular Expression.
There is a function in the regular expression library(re) that compares two strings for us. re.match(pattern, string) is a function that returns an object, to find whether a match is find or not we have to typecast it into boolean.
- pattern: the pattern against which you want to check
- string: the string you want to check for the pattern
Return: Match object
Let’s see an example:
Method 2: Using Set.
Set is a built-in data type in Python. We are using issubset() function of a set that returns True if all characters of a set are present in a given set Otherwise False.
- set: Represents that set in which the subset has to be searched
Return: boolean value
Let’s see an example:
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method : Using replace() and len() methods
Method : Using operator.countOf() method
Time Complexity: O(N)
Auxiliary Space : O(1)
Method: Using the filter() function with a lambda function.
- Initialize the allowed_chars string with all the valid characters.
- Initialize the string variable with the input string.
- Use the filter() function with a lambda function to filter out any characters in string that are not in allowed_chars.
- Convert the filtered object to a list and check if its length is equal to the length of the original string.
- If the lengths are equal, output True. Otherwise, output False.
The time complexity of the filter() function is O(n), where n is the length of the input string. The time complexity of the list() function is also O(n). The time complexity of the comparison operation len(list(filtered)) == len(string) is O(1). Therefore, the overall time complexity of the code is O(n).
The space complexity of the filtered list is O(n), where n is the length of the input string. The space complexity of the list() function is also O(n). Therefore, the overall auxiliary space complexity of the code is O(n).
Please Login to comment...