Python Validate String using regex

How to validate string using regex in python programming ?

In python programming, compile function in re python module is used to check the regex pattern in a string.

re.compile method returns true if pattern is matched otherwise return false.

import re                                                                       
pattern = re.compile(r"[A-Za-z\s]+")                                            
text = raw_input ("Please enter text: ")                                        
    print("Valid text!")                                                        
    print("Invalid text!")   

This code validates the text with regex pattern and returns valid text if regular expression pattern matches, otherwise return invalid text.

$ python 
Please enter text: test in progress
Valid text!
$ python 
Please enter text: 243242 2424
Valid text!
$ python 
Please enter text: 878
Invalid text!

How to validate number using regex in python programming ?

If we use different regex pattern based on number format, re.compile function is also used to validate the string using number pattern format.

import re                                                                       
pattern = re.compile(r"[[0-9]+")                                                
number = raw_input ("Please enter number: ")                                        
    print("Valid number!")                                                        
    print("Invalid number!")                                                                                                                              

This python code is used to check whether entered number is valid number or not.

]$ python 
Please enter number: 23242
Valid number!
$ python 
Please enter number: test
Invalid number!

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter