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: ")                                        
                                                                                
if pattern.search(text):                                                        
    print("Valid text!")                                                        
else:                                                                           
    print("Invalid text!")   

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

Output:
$ python pattern.py 
Please enter text: test in progress
Valid text!
$ python pattern.py 
Please enter text: 243242 2424
Valid text!
$ python pattern.py 
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: ")                                        
                                                                                
if pattern.search(number):                                                        
    print("Valid number!")                                                        
else:                                                                           
    print("Invalid number!")                                                                                                                              

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

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

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^