
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
Example
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)
Output
The string is : Python The string contains the defined characters The string is : PythonInterpreter The doesn’t string contain the defined characters
Explanation
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.
- Related Articles
- Java Program to check if the String contains only certain characters
- Check if a string contains only alphabets in Java using Regex
- How to check if a string only contains certain characters in Python?
- How to check if a string contains only decimal characters?
- 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?
- Python Program to check if a string starts with a substring using regex
- Check whether the String contains only digit characters in Java
- Check if string contains special characters in Swift
- How to check if a string contains only whitespace letters in Python?
- 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?
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a string contains only alphabets in Java using ASCII values

Advertisements