Skip to content
Related Articles

Related Articles

Improve Article
Python – Check if String Contain Only Defined Characters using Regex
  • Difficulty Level : Medium
  • Last Updated : 29 Dec, 2020

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

Examples:

Input: ‘657’ let us say regular expression contain following characters-
(‘78653’)
Output: Valid
Explanation:
The Input string only consist of characters present in the given string

Input: ‘7606’ let us say regular expression contain following characters-
(‘102’) 
Output: Invalid

Approach:



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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :