Regular Expressions in Python

Regular Expressions in Python make life easier in programming. “import re” should be used to use regular expressions in Python. re.findall() and re.search() are used. import re should be used to make use of Regular Expressions in Python.

re.search():

The search method returns true or false depending on whether the string matches the regular expression and returns the first matching value.

Example:

import re;
strInfo = input( 
    'Enter a String with numbers in the middle: '
);
numFound = re.search( '[0-9]+', strInfo );
print ( 'numFound is ', numFound );

re.findall():

The findall method returns list of all the matched string. If there is no matches, then it will return empty list.

Example:

import re;
strInfo = input( 
    'Enter a String with numbers in the middle: '
);
listNumbers = re.findall( '[0-9]+', strInfo );
for num in listNumbers :
    print ( num );
Regular Expressions in Python
Regular Expressions in Python

Leave a Reply