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.

Python supports regular expressions. It has a special library to work with these. I have shared best examples for your quick reference.
Python Regular Expressions

I am not sharing here how to play tennis. My intention is if you just follow ideas, you can play tennis today.

Python Regular Expressions

  1. What is a regular expression?
  2. How does python support
  3. 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.

Two Main Reasons Why We use Regular Expressions

  1. Data mining - to get required data if it is present are not
  2. 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.
  1. If a match found it returns the String
  2. If there is no match it does return null
Best Example for Regular Expression

>>> 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.

Related Posts

Comments

Popular posts from this blog

Hyperledger Fabric: 20 Real Interview Questions

How to Fix Python Syntax Errors Quickly

7 AWS Interview Questions asked in Infosys, TCS