Play with Python Regular Expressions Like Tennis
Regular Expressions are something like to find a matching string in another string. You will get either 'True' or 'False' as a response.
I am not sharing here how to play tennis. My intention is if you just follow ideas, you can play tennis today.
>>> '213-867-5309' in haystack
True
![]() |
Python Regular Expressions |
Python Regular Expressions
- What is a regular expression?
- How does python support
- Best examples
Let us start - What is Regular Expression.
>>> haystack = 'My phone number is 213-867-5309.'>>> '213-867-5309' in haystack
True
This is just a fundamental use of the regular expression. The real use of Regular Expression comes here. That is - to find if the main has any valid phone number.
Regular expressions also called regexes.
>>> import re
>>> re.search(r'fox', 'The quick brown fox jumped...')
<_sre.SRE_Match object; span=(16, 19), match='fox'>
Notes: The returned string is 'fox'.
How to Use the group to Get matching String
>>> match = re.search(r'fox', 'The quick brown fox jumped...')
>>> match.group() 'fox'
Notes: The returned string is 'fox'.
How to get multiple Matches
>>> import re >>> re.findall(r'o', 'The quick brown fox jumped...')
['o', 'o']
Notes: It returns multiple strings.
Regular expressions also called regexes.
Two Main Reasons Why We use Regular Expressions
- Data mining - to get required data if it is present are not
- Data validations - to get an answer if the received string is valid or not.
How Python Supports
Python has its own regular expression library. That is called re. What you need to do is just import it.
>>>import re
How Python responds when data matches and not matches.
- If a match found it returns the String
- If there is no match it does return null
Best Example for Regular Expression
>>> re.search(r'fox', 'The quick brown fox jumped...')
<_sre.SRE_Match object; span=(16, 19), match='fox'>
Notes: The returned string is 'fox'.
How to Use the group to Get matching String
>>> match.group() 'fox'
Notes: The returned string is 'fox'.
How to get multiple Matches
['o', 'o']
Notes: It returns multiple strings.
Related Posts
Comments
Post a Comment
Thanks for your message. We will get back you.