- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to check if String contains only Defined Characters using Regex
When it is required to check if a given string contains specific characters using regular expression, a regular expression pattern is defined, and the string is subjected to follow this pattern.
Below is a demonstration of the same
import re def check_string(my_string, regex_pattern): if re.search(regex_pattern, my_string): print("The string contains the defined characters only") else: print("The doesnot string contain the defined characters") regex_pattern = re.compile('^[Python]+$') my_string_1 = 'Python' print("The string is :") print(my_string_1) check_string(my_string_1 , regex_pattern) my_string_2 = 'PythonInterpreter' print("\nThe string is :") print(my_string_2) check_string(my_string_2, regex_pattern)
The string is : Python The string contains the defined characters The string is : PythonInterpreter The doesn’t string contain the defined characters
The required packages are imported.
A method named ‘check_string’ is defined, and it takes the string and a regular expression as parameters.
The ‘search’ method is called and checked to see if a specific set of characters is present in the string.
Outside the method, the ‘compile’ method is called on the regular expression.
The string is defined and is displayed on the console.
The method is called by passing this string.
The output is displayed on the console.
- Check if a string contains only alphabets in Java using Regex
- Java Program to check if the String contains only certain characters
- How to check if a string contains only decimal characters?
- How to check if a string only contains certain characters in Python?
- How to check if a unicode string contains only numeric characters in Python?
- Python program to check if a string contains all unique characters
- How to check if a Python string contains only digits?
- Check if string contains special characters in Swift
- Check whether the String contains only digit characters in Java
- How to check if a string contains only whitespace letters in Python?
- Python Program to check if a string starts with a substring using regex
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a string contains only alphabets in Java using ASCII values
- How to check if a string contains only lower case letters in Python?
- How to check if a string contains only upper case letters in Python?