Regular Expressions in Python | Python Tutorial - Day #95 (2024)

Table of Contents
Introduction Video FAQs

Introduction

Access the Playlist: www.youtube.com/playlist
Link to the Repl: replit.com/@codewithharry/95-Day-95-Regular-Expressions
Join Replit the browser-based IDE used in this course - join.replit.com/code-with-harry-100-doc
►Checkout my English channel here: www.youtube.com/channel/UC7btqG2Ww0_2LwuQxpvo2HQ
►Instagram: www.instagram.com/codewithharry

python, C, C++, Java, JavaScript and Other Cheetsheets [++]:
Playlist: www.youtube.com/playlist

►Learn in One Video[++]:
Python[15 Hr]: www.youtube.com/watch
Python Advance[3.5 Hr]: www.youtube.com/watch
Python[1 Hr]: www.youtube.com/watch
Python[2 Hr]: www.youtube.com/watch
Python[15 Min]:www.youtube.com/watch
JavaScript[1 Hr]: www.youtube.com/watch
C[1.3 Hr]-www.youtube.com/watch
php[1 Hr]: www.youtube.com/watch
php[2.3 Hr]:www.youtube.com/watch
php[Project]- www.youtube.com/watch
HTML[30 Min]:www.youtube.com/watch
CSS[8.5 Hr]:www.youtube.com/watch
CSS[1.4 Hr]:www.youtube.com/watch
Wordpress[3.2 Hr]:www.youtube.com/watch
Angular[2 Hr]:www.youtube.com/watch
Java[2.3 Hr]:www.youtube.com/watch
Web Scraping[1 Hr]:www.youtube.com/watch
MongoDB[2 Hr]:www.youtube.com/watch
Numpy[1 Hr]:www.youtube.com/watch
Android Dev[12 Hr]- www.youtube.com/watch
Linux[1 Hr]:www.youtube.com/watch
JQuery[1.1 Hr]:www.youtube.com/watch
Git and GitHub[1.1 Hr]:www.youtube.com/watch

►Complete course [playlist]:
React: www.youtube.com/playlist
Python-www.youtube.com/playlist
OOP Python-www.youtube.com/playlist
Java:www.youtube.com/playlist
JavaScript- www.youtube.com/playlist
PHP-www.youtube.com/playlist
C-www.youtube.com/playlist
C++-www.youtube.com/playlist
Git & GitHub-www.youtube.com/playlist
Android Dev- www.youtube.com/playlist
Python GUI- www.youtube.com/playlist
Web Development- www.youtube.com/playlist
Python Django:www.youtube.com/playlist
Projects Using HTML, CSS & Javascript- www.youtube.com/playlist
Data Structure and Algo:www.youtube.com/playlist

Follow Me On Social Media
►Website (created using Django Rest & Angular): www.codewithharry.com
►Facebook: www.facebook.com/CodeWithHarry
►Instagram: www.instagram.com/codewithharry/
Twitter: twitter.com/CodeWithHarry
Comment "#HarryBhai" if you read this 😉😉

Video

Topic for today's video is 'regular Expressions' "How can we use Regular Expressions in Python?", And "What are Regular.

Expressions?" You might not know that No problems, because in this video I am going to make.

You understand everything practically Let's move to the computer screen And.

Let's get started: [ [S, [ST, [STA, [STAR, [START, [STARTI, [STARTIN, [STARTING, [STARTING, [STARTING, T, [STARTING, TH, [STARTING, THE, [STARTING, THEM, [STARTING, THEME OK.

So let's explore 'regular Expression' As.

You can see I've made a Repl and I've opened it And before explaining 'regular Expression', Let me first tell you why you have to use it Firstly, you don't have to use 'regular Expression' for basic matching Because for basic matching.

You can use these keywords or you can also check it by using 'for Loop' So.

There's no point: Yes I know you can check complex pattern by using For Loop & making more efforts.

But 'regular Expression' were made so that you don't have to make more efforts.

And you get everything built-in To use, 'regular Expression'! You have to import 're', package, It's, a built-in package So.

This was the first step which I wanted to tell you.

You can import 're' module Then, there are 2 things, The.

First one is 'pattern' Suppose.

This is my patters And.

This is my text.

As, you all know.

You can write Python string in triple-single, quotes(''', '''), Suppose, I, open Wikipedia, Yes!, OK! I'll write any thing: "Wikipedia" I'll copy it And I'll paste it here.

So this is my text.

I've written my text here, And.

It contains a lot of text.

This is my pattern & this.

Is my text? And I have to search this text through pattern.

Means I want to search where this pattern is, in my text, So 're' package, which means I, can do that with the help of 'regular Expression' Now.

How will I do that? There's a function? "Re.Search()" So? Firstly, let me show you the pattern.

Suppose I want to search "was" from this text So.

After doing this, if I print(match) So, it won't tell me, where "was" was present in this text But.

It will definitely tell me whether the "was" exist in the text or not.

Now I'll run it, so look, "Match "Was" found", And "span=(17, 20)" So.

This is how I can tell if "Was" exist in this text or not Now you'll.

Think what's going on & What's the point of doing all this? "I could have done it with the help of these keywords" Yes.

You could have But how about if I make the pattern a little bit.

Complex? And here comes the main topic: 'regular Expression' Now.

Let me define Meta characters.

Meta Characters are used to make patterns.

For, eg., If I.

Ask you to search or Let's say we have "Cyclone" written here.

Here.

We have "Cyclone" And.

Here we have "Dyclone" Suppose it's written here Now.

If I ask you to tell me where we have "yclone", starting with capital letters.

Which means "Dyclone" with Capital D "Eyclone", with Capital E and "Zyclone", with Capital Z You have to search only these Now you'll be confused and you'll, say: I'll, create my custom logic.

But you'll.

Ask me for time to think So to skip that time.

I'm here to tell you about 'regular Expression' Now I can specify here that the first letter of the word should be a Capital letter, and that word should also contain "yclone" pattern.

= "capitalyclone" I can specify it in this way.

I'll add "r" here, and this string will now be a raw string.

Let me tell you what is raw string Suppose if I write "back-slash(n)", then it will print a raw string and won't parse escape sequence character.

I've added a square-bracket here, I specified that any character will work for me between Capital A and Capital Z But.

That word must also contain "yclone" What I've done here.

Is, I've made a character class I know many of you will be scared and say we're not getting what you're saying, but pay attention.

On my words, Any character between Capital A & Capital, Z Must appear at-least once I need a word which contain any character between Capital A and Capital Z, along with "yclone" So, look, (+) means "One or more occurrences", So, If I, add a (+) here and run it.

So "Cyclone" has been matched But, "dyclone" didn't match, and I'll have to see why.

It didn't match because "re.search" stops at the first match.

You will say that I just do not want to know whether it's matching or not I'm not interested in first occurrence I'm interested in all the occurrences from the text.

So for that I'll write, "match, =, re.finditer", And I'll write the pattern & text in the same format.

And now I'll write, "for, match in..." Let me change it to "matches" And.

Here I'll write, "print(match)" It's a match, object, Now.

If I run it so it'll throw all the matches.

So here..

As, you can see it threw 2 matches "Cyclone" & "Dyclone" And.

It also displayed the span of those occurrences.

Now I can write "for match in matches" "print(match.span())" By.

This I'll get it's span Now.

If I show you it's type..., So look, it's type will be printed here.

And, it's type is a Tuple Do you get.

The point? It means that I can do something like this I'll write here.

"Print(Match(*Match.

span( )))" If I do slicing for the match in this way, Such that if I write here "match.span()[0]" And here, if I write, "match.span()[1] Then I'll get those "Cyclone" & "Dyclone" Now, it is saying "No such group" Let me check.

What's the problem here, I wrote: "match.span()" I've to write "text" instead of "match" So I asked it to print "match.span()[0]" & "match.span()[1]".

Which means 0 & 7 of the text.

Now, it is saying.

"String indices must be integers", I think they are not the integers So.

If I run "print(match.span()[0]"..

It's saying "It's, not an integer" So.

Let me see what's wrong: If I only print "match.span()[0]" Then.

What am I getting? I'm, getting "0" Oh OK! I, have to add colon(:).

Instead of comma(,) I made a little mistake, but now see I'll get "Cyclone" & "Dyclone" as output So.

This is how you can do matching of 'regular Expressions' Now again, 'regular Expressions' is quite a big topic.

You'll get to see a lot of things.

And it'll take a lot of time for you to learn: 'regular Expressions' I've, given a link here , so that you'll get to know about all the meta characters.

And.

That link contains a lot of things which you need to learn about Now.

If I talk about backslash(\) It marks the next character as a special character or a literal, For example, n matches the character n, whereas (\)n matches a newline, character., The sequence, \\ matches \ Which means it ends the specialness of (\) character.

So.

There are a lot of things which can be done.

So.

You have to understand the pattern And.

If you learn to write a good pattern, then you'll get all the things from the text that you want Or.

If you want to find, if that exist in the text or not Then, you can do that too.

It's.

Quite easy.

If you learn to write pattern, Now I want to tell you about a website, which is quite important.

First of all the python docs are quite important.

This is for those who wants to be a master of 'regular.

Expressions' It'll be like a book.

If you start reading it from here It's a quite detailed documentation, But yes, once you completed 100 Days Of Code And, you wants to be a master of 'regular Expressions'.

Then you can become one from this documentation.

Another website which I want to talk about.

Is...

I forgot, it's name , but look here it is "regexr.com".

It'll definitely appear on Google I knew that Look, from A-Z.

Then it becomes group from bracket.

Let me show you.

If I add this bracket And.

If I want to print one from them that could either be "H", , "W" or "R" What does "\w" means? If you hover on it then you'll know "Matches any word: character" Any, word character and more than one word character: Now look, I've, written "/[HWR], +\w ".

It means that..

Any character from "H", "W" or "R" And.

Then "\w".

Then there "+", which defines that it'll take any character with multiple number of occurrences.

Which means "It would start with "H", "W" or "R", and then any number of characters Here's a cheat-sheet.

And if you click on it Then you can learn a lot of things.

Let me tell you: "." means any character except new line So if I add "." after HWR, then...., Then it'll match 2 characters, any one from [HWR] and then any character, So it matched "Re" "He", "Ro", Now.

If I add double-dots(..) here, then it'll match three characters: If I make a group here.

Defining "there must be two characters after [HWR] and after that it should contain 'e', " So look, it matched this "Reference" I defined.

There must be any character from [HWR] and two characters and then it should contain "E".

Now I want "E" along with "R", so it got match with this So.

This is how you can make patterns And in Python.

You can either use 'match' If, you use 'match', so it return "None".

If it's unable to find Suppose.

If I try to find this, then it'll show nothing Because the matches are empty But.

If I show you, then this will return "None", because this pattern didn't match.

This is how you can start your journey of 'regular, Expressions'.

I know it's a little bit complicated.

If you're, a beginner, When I started to learn: 'regular Expressions', , I.

Also used to think I don't need this But as you progress in programming, you'll see it in JavaScript, too And you'll see it almost in every programming.

Language And it'll only make things easier, not difficult, So.

You must learn it and let me link this website here, So that you can explore it.

Let me add this here: So, don't forget to visit this website and it's cheat-sheet.

It contains a lot of things which you'll understand And.

The best part is that.

It explains 'regular Expressions' to you briefly, When &.

Why is it matching and and not all the stuff like that? So you play around with that by clicking here.

I hope you understood, 'regular, Expressions' And.

You won't understand this briefly until you practice it That's it for this video guys And make sure to access this play-list.

If you haven't yet Thank you so much guys for watching this.

Video :) And I'll see you next time.

Regular Expressions in Python | Python Tutorial - Day #95 (2024)

FAQs

How do you create a regular expression in Python? ›

The solution is to use Python's raw string notation for regular expressions; backslashes are not handled in any special way in a string literal prefixed with 'r' , so r"\n" is a two-character string containing '\' and 'n' , while "\n" is a one-character string containing a newline.

What is regular expression explain with example in Python? ›

Regular expressions are a powerful language for matching text patterns. This page gives a basic introduction to regular expressions themselves sufficient for our Python exercises and shows how regular expressions work in Python. The Python "re" module provides regular expression support. str = 'an example word:cat!!'

What are the regular expression in Python? ›

Regular Expression Syntax. A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).

How to use RegEx to extract string Python? ›

Use re.search() to extract a substring matching a regular expression pattern. Specify the regular expression pattern as the first parameter and the target string as the second parameter.

What is regular expression examples? ›

A regular expression pattern is composed of simple characters, such as /abc/ , or a combination of simple and special characters, such as /ab*c/ or /Chapter (\d+)\.\d*/ . The last example includes parentheses, which are used as a memory device.

How do you create a regex function? ›

As mentioned above, you can either use RegExp() or regular expression literal to create a RegEx in JavaScript. const regex1 = /^ab/; const regex2 = new Regexp('/^ab/'); In JavaScript, you can use regular expressions with RegExp() methods: test() and exec() .

Why do we need regular expression in Python? ›

In NLP, regular expressions are used to remove the unnecessary words i.e., stop words from the text—thus helps in data cleaning. Regex is also used in analyzing the texts and thus helps in the prediction of the algorithm to process the data.

How do you use regular expressions? ›

Examples:
  1. To match a sequence of literal characters, simply write those characters in the pattern.
  2. To match a single character from a set of possibilities, use square brackets, e.g. [0123456789] matches any digit.
  3. To match zero or more occurrences of the preceding expression, use the star (*) symbol.
May 30, 2023

What is a real life example of regular expression? ›

Best use cases of regular expressions

[^@ \.]{ 2,}$ => then one dot and then at least 2 characters which do not include @, space and dot. Note that, we have added backslash before dot(.), Just dot(.) without backslash means it will match any character.

Is Python good for regular expressions? ›

One of today's most popular programming languages, Python has many powerful features that enable data scientists and analysts to extract real value from data. One of those, regular expressions in Python, are special collections of characters used to describe or search for patterns in a given string.

What is a regular expression coding? ›

A Regular Expression (or Regex) is a pattern (or filter) that describes a set of strings that matches the pattern. In other words, a regex accepts a certain set of strings and rejects the rest. A regex consists of a sequence of characters, metacharacters (such as .

What is the most common regex Python? ›

re. sub() is one of the most commonly used functions in Python regex. It tries to find a pattern ( pattern )in a string ( string ) and replace it with the provided replacement string ( repl ).

How do you split a string into words in RegEx Python? ›

Regex to split String into words with multiple word boundary delimiters. In this example, we will use the [\b\W\b]+ regex pattern to cater to any Non-alphanumeric delimiters. Using this pattern we can split string by multiple word boundary delimiters that will result in a list of alphanumeric/word tokens.

How to find string matches to RegEx? ›

If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.

How to get data from RegEx? ›

In order to create an extracting rule that uses RegEx you should select a 'Regular Expression' as the data field type. Another way of applying RegEx is to click on 'Add Filter' 'Find ...' 'Find by Regex'. In the following example we demonstrate the usage of RegEx in AlgoDocs.

How to install regex in Python? ›

Type "cmd" in the search bar and hit Enter to open the command line. What is this? Type “ pip install regex ” (without quotes) in the command line and hit Enter again. This installs regex for your default Python installation.

What is the syntax for regular expression? ›

[.-.] (Range Expression): Accept ANY ONE of the character in the range, e.g., [0-9] matches any digit; [A-Za-z] matches any uppercase or lowercase letters. [^...]: NOT ONE of the character, e.g., [^0-9] matches any non-digit. Only these four characters require escape sequence inside the bracket list: ^ , - , ] , \ .

What does \r do in Python? ›

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

How do you use regular expressions in Pandas Python? ›

Pandas and regular expressions
  1. str. contains(pattern) — This function checks for a pattern in a column (Series) to return True and False values (a mask) where the pattern matches. ...
  2. str. extract(pattern, expand, flags) — To use this function, we must define groups using parentheses inside the pattern. ...
  3. str.
Nov 9, 2022

Top Articles
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 5341

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.