Python: How to Writes Regular Expressions

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

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
>>> re.search(r'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 = re.search(r'fox', 'The quick brown fox jumped...')
>>> match.group() '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.

Comments

Popular Posts

Hyperledger Fabric: 20 Real Interview Questions

7 AWS Interview Questions asked in Infosys, TCS

How to Fix Python Syntax Errors Quickly

Python 'getsizeof' Command the Real Purpose

Blue Prism complete tutorials download now

Vi Editor to Quit use Esc and Colon

Python Dictionary Vs List With Examples

AWS Vs Azure Load Balancers Top Insights

Tokenization: Vault based Vs Vault-less

5 HBase Vs. RDBMS Top Functional Differences