Ad Code

How to Write Regular Expression in Python Quickly

Regular Expressions are something like finding 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.

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

Python Regular Expressions

  1. What is a regular expression?
  2. How does python support
  3. Best examples

1. What is Regular Expression?

>>> haystack = 'My phone number is 213-867-5309.' 
>>> '213-867-5309' in haystack

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.

2. Why We Need 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.

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

ii). 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 will return null

iii). How to Write Code for Regular Expression

>>> import re
>>>'fox', 'The quick brown fox jumped...')
<_sre.SRE_Match object; span=(16, 19), match='fox'>

Notes: The returned string is 'fox'.

iv). How to Use the group to Get matching String

>>> match ='fox', 'The quick brown fox jumped...')
>>> 'fox'

Notes: The returned string is 'fox'.

v). How to get multiple Matches

>>> import re >>> re.findall(r'o', 'The quick brown fox jumped...')
['o', 'o']

Notes: It returns multiple strings.

Post a Comment