Open In App

Python – Check if String Contain Only Defined Characters using Regex

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets.

Examples:

Input: ‘657’ let us say regular expression contains the following characters- (‘78653’)

Output: Valid

Explanation: The Input string only consists of characters present in the given string.

Input: ‘7606’ let us say regular expression contains the following characters-
(‘102’) 

Output: Invalid

Explanation: The input string consists of characters not present in given string.

Algorithm

Step 1: Define the pattern of the string using RegEx.

Step 2: Match the string with the specified pattern

Step 3: Print the Output

Check if String Contains Only Defined Characters using Regex

The method or approach is simple we will define the character set using a regular expression. The regular expression is a special pattern or sequence of characters that will allow us to match and find other sets of characters or strings. 

Functions Used:

  • compile(): Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions.
  • search(): re.search() method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.

Below is the implementation.

Python3




# _importing module
import re
def check(str, pattern):
    # _matching the strings
    if re.search(pattern, str):
        print("Valid String")
    else:
        print("Invalid String")
# _driver code
pattern = re.compile('^[1234]+$')
check('2134', pattern)
check('349', pattern)


Output:

Valid String
Invalid String

Note: You can also use re.match() in place of re.search()

Time complexity :  O(n)
Space Complexity : O(1)


Previous Article
Next Article

Similar Reads

Python | Ways to check string contain all same characters
Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same. Method #1: Using Naive Method [Inefficient] C/C++ Code # Python code to demonstrate # to check whether string contains # all characters same or not # Initialising string list ini_list = [
5 min read
How to check if a string starts with a substring using regex in Python?
Prerequisite: Regular Expression in Python Given a string str, the task is to check if a string starts with a given substring or not using regular expression in Python. Examples: Input: String: "geeks for geeks makes learning fun" Substring: "geeks" Output: True Input: String: "geeks for geeks makes learning fun" Substring: "makes" Output: FalseChe
3 min read
How to check a valid regex string using Python?
A Regex (Regular Expression) is a sequence of characters used for defining a pattern. This pattern could be used for searching, replacing and other operations. Regex is extensively utilized in applications that require input validation, Password validation, Pattern Recognition, search and replace utilities (found in word processors) etc. This is du
6 min read
How to remove array rows that contain only 0 using NumPy?
Numpy library provides a function called numpy.all() that returns True when all elements of n-d array passed to the first parameter are True else it returns False. Thus, to determine the entire row containing 0's can be removed by specifying axis=1. It will traverse each row and will check for the condition given in first parameter. Example: data=[
2 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
How to Remove repetitive characters from words of the given Pandas DataFrame using Regex?
Prerequisite: Regular Expression in Python In this article, we will see how to remove continuously repeating characters from the words of the given column of the given Pandas Dataframe using Regex. Here, we are actually looking for continuously occurring repetitively coming characters for that we have created a pattern that contains this regular ex
2 min read
Python | Check if string matches regex list
Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let's discuss a way in which this task can be performed. Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we cre
4 min read
Find all the patterns of “1(0+)1” in a given string using Python Regex
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern. Examples: Input : 1101001 Output : 2 Input : 1000
2 min read
The most occurring number in a string using Regex in python
Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python. It is guaranteed that no two element have the same frequency Examples: Input :geek55of55geeks4abc3dr2 Output :55Input :abcd1def2high2bnasvd3vjhd44Output :2Approach:Extract all the numbers from a string str usi
2 min read
Validate an IP address using Python without using RegEx
Given an IP address as input, the task is to write a Python program to check whether the given IP Address is Valid or not without using RegEx. What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists
2 min read
Practice Tags :