{"id":20050,"date":"2022-09-18T22:53:00","date_gmt":"2022-09-18T17:23:00","guid":{"rendered":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/"},"modified":"2024-11-18T18:19:28","modified_gmt":"2024-11-18T12:49:28","slug":"regular-expression-in-python","status":"publish","type":"post","link":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/","title":{"rendered":"Introduction to Regular Expression in Python | Regex in Python"},"content":{"rendered":"\n<p>Regular Expression(regex or RE for short) as the name suggests is an expression which contains a sequence of characters that define a search pattern. Take an example of this simple Regular Expression :<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b <\/pre>\n\n\n\n<p>This expression can be used to find all the possible emails in a large corpus of text. This is useful because otherwise, you will have to manually go through the whole text document and find every email id in it. After going through this article you\u2019ll know how the above Regular Expression works and much more. We can use different programming languages such as <a aria-label=\"Java (opens in a new tab)\" href=\"https:\/\/www.mygreatlearning.com\/blog\/java-tutorial-for-beginners\/\" target=\"_blank\" rel=\"noreferrer noopener\">Java<\/a>, <a aria-label=\"Python (opens in a new tab)\" href=\"https:\/\/www.mygreatlearning.com\/blog\/python-tutorial-for-beginners-a-complete-guide\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python<\/a>, <a aria-label=\"JavaScript (opens in a new tab)\" href=\"https:\/\/www.mygreatlearning.com\/blog\/javascript-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">JavaScript<\/a>, PHP and many more to implement Regular Expressions but there are certain variations in its implementation across these languages. So now let us see the subtopics we are going to cover in this article:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#what-is-regular-expression-in-python\">What is Regular Expression in Python?<\/a><\/li>\n\n\n\n<li><a href=\"#how-to-write-regular-expression-in-python\">How to write Regular Expression in Python?<\/a><\/li>\n\n\n\n<li><a href=\"#examples-of-regular-expression-in-python\">Examples of Regular Expression in Python<\/a><\/li>\n\n\n\n<li><a href=\"#regular-expression-program-in-python\">Regular Expression program in Python<\/a>\n<ol class=\"wp-block-list\">\n<li><a href=\"#email-validation-in-python\">Email Validation in Python using Regular Expression<\/a><\/li>\n\n\n\n<li><a href=\"#validate-mobile-number-using-python\">Validate mobile number using Regular Expression in Python<\/a><\/li>\n<\/ol>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-regular-expression-in-python\"><strong>What is Regular Expression in Python?<\/strong><\/h2>\n\n\n\n<p>In Python, a Regular Expression (REs, regexes or regex pattern) are imported through re module which is an ain-built in Python so you don\u2019t need to install it separately.<\/p>\n\n\n\n<p>The re module offers a set of functions that allows us to search a string for a match:<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Function<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong> Description<\/strong> <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">findall<\/td><td class=\"has-text-align-center\" data-align=\"center\">  Returns a list containing all matches   <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> compile <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &nbsp;Returns a regex objec <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> search <\/td><td class=\"has-text-align-center\" data-align=\"center\"> Returns a Match object if there is a match anywhere in the string <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> split <\/td><td class=\"has-text-align-center\" data-align=\"center\">  Returns a list where the string has been split at each match <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> sub <\/td><td class=\"has-text-align-center\" data-align=\"center\"> Replaces one or many matches with a string <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> subn&nbsp; &nbsp;  <\/td><td class=\"has-text-align-center\" data-align=\"center\"> Similar to sub except it returns a tuple of 2 items containing the new string and the number of substitutions made. <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> group&nbsp; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> Returns a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern  <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> match <\/td><td class=\"has-text-align-center\" data-align=\"center\"> Similar to search, but only searches in the first line of the text  <\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>We shall use all of these methods once we know how to write Regular Expressions which we will learn in the next section.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-to-write-regular-expression-in-python\"><strong>How to write Regular Expression in Python?<\/strong><\/h2>\n\n\n\n<p>To learn how to write RE, let us first clarify some of the basics. In RE we use either literals or meta characters.literals are the characters themselves and have no special meaning. Here is an example in which I use literals to find a specific string in the text using findall method of re module.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"Hello my name is Hussain\"\nprint(re.findall(r\"Hussain\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['Hussain']<\/p>\n\n\n\n<p>As you can see we used the word \u2018Hussain\u2019 itself to find it in the text. This may not seem a good idea when we have to extract thousands of names from a corpus of text. To do that we need to find a specific pattern and use meta-characters.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"meta-characters\"><strong>Meta-characters <\/strong><\/h4>\n\n\n\n<p>Metacharacters are characters with a special meaning and they are not interpreted as they are which is in the case of literals. We may further classify meta-characters into identifier and modifiers.<\/p>\n\n\n\n<p>Identifiers are used to recognise a certain type of characters. For example, to find all the number characters in a string we can use an identifier \u2018\/d\u2019<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"Hello I live on street 9 which is near street 23\"\nprint(re.findall(r\"\\d\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['9', '2', '3']<\/p>\n\n\n\n<p>But there seems to be a problem with this. It only returns single-digit numbers and even worst even split the number 23 into two digits. So how can we tackle this problem, can using two \\d help?<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"Hello I live on street 9 which is near street 23\"\nprint(re.findall(r\"\\d\\d\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['23']<\/p>\n\n\n\n<p>Using two identifiers did help, but now it can only find two-digit numbers, which is not what we wanted.<\/p>\n\n\n\n<p>One way to solve this problem will be modifiers, but first, here are some identifiers that we can use in Python. We shall use some of them in the examples we are going to do in the next section.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"> \\d = any number\n\\D = anything but a number\n\\s = space\n\\S = anything but a space\n\\w = any letter\n\\W = anything but a letter\n. = any character, except for a new line\n\\b = space around whole words\n\\. = period. must use a backslash, because \u2018 . \u2018 normally means any character.<\/pre>\n\n\n\n<p>Modifiers are a set of meta-characters that add more functionality to identifiers. Going back to the example above, we will see how we can use a modifier \u201c + \u201d to get numbers of any length from the string. This modifier returns a string when it matches 1 or more characters.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"Hello I live on street 9 which is near street 23\"\nprint(re.findall(r\"\\d+\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['9', '23']<\/p>\n\n\n\n<p>Great! finally, we got our desired results. By using \u2018+\u2019 modifier with the \/d identifier, I can extract numbers of any length. Here are few of the modifiers that we are also going to use in the examples section ahead.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"> + = match 1 or more\n? = match 0 or 1 repetitions.\n* = match 0 or MORE repetitions\n$ = matches at the end of string\n^ = matches start of a string\n| = matches either\/or. Example x|y = will match either x or y\n[] = A set of characters in which we define range, or \"variance\"\n{x} = expect to see this amount of the preceding code.\n{x,y} = expect to see this x-y amounts of the precedng code<\/pre>\n\n\n\n<p>Did you notice we are using the r character at the start of all RE, this r is called a raw string literal. It changes how the string literal is interpreted. Such literals are stored as they appear.<\/p>\n\n\n\n<p>For example, \\ is interpreted as an escape sequence usually but it is just a backslash when prefixed with an r.&nbsp; You will see what this means with special characters. Sometimes, the syntax involves backslash-escaped characters, and to prevent these characters from being interpreted as escape sequences we use this raw string literals.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"examples-of-regular-expression-in-python\"><strong>Examples of Regular Expression in Python<\/strong><\/h2>\n\n\n\n<p>Let us explore some of the examples related to the meta-characters. Here we are going to see how we use different meta-characters and what effect do they have on output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"get out Of my house !!!\"\nprint(re.findall(r\"\\w+\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['get',&nbsp;'out',&nbsp;'Of',&nbsp;'my',&nbsp;'house']<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"get out Of my house !!!\"\nprint(re.findall(r\"\\w{2}\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['et',&nbsp;'ut',&nbsp;'Of',&nbsp;'my',&nbsp;'se'] <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"abc abcccc abbbc ac def\"\nprint(re.findall(r\"\\bab*c\\b\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['abc',&nbsp;'abbbc',&nbsp;'ac'] <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"abc abcccc abbbc ac def\"\nprint(re.findall(r\"\\bab+c\\b\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['abc',&nbsp;'abbbc']  <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"get out Of my house !!!\"\nprint(re.findall(r\"\\b\\w{2}\\b\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['Of',&nbsp;'my'] <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring=\"name and names are 23 blah blah\"\nprint(re.findall(r\"\\b\\w+es?\\b\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['name',&nbsp;'names',&nbsp;'are']&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring='''I am Hussain Mujtaba and M12  !a\n'''\nprint(re.findall(r\"M.....a\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['Mujtaba',&nbsp;'M12&nbsp;&nbsp;!a'] <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring='''123345678\n'''\nprint(re.findall(r\"&#91;123]\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['1',&nbsp;'2',&nbsp;'3',&nbsp;'3']<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\n string='''123345678\n '''\n print(re.findall(r\"&#91;^123]\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['4',&nbsp;'5',&nbsp;'6',&nbsp;'7',&nbsp;'8',&nbsp;'\\n'] <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring='''\nhello I am a student from India\n'''\nprint(re.findall(r\"&#91;A-Z]&#91;a-z]+\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['India'] <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring='''\nhello I am a student from India\n'''\nprint(re.findall(r\"\\b&#91;A-Ia-i]&#91;a-z]+\\b\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['hello',&nbsp;'am',&nbsp;'from',&nbsp;'India'] <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring='''\nhello I am a student from India. Hello again\n'''\nprint(re.findall(r\"\\b&#91;h|H]\\w+\\b\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['hello',&nbsp;'Hello']&nbsp; <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring='''\nhello I am a student from India and heere is now\n'''\nprint(re.findall(r\"(&#91;a-z])\\1\",string))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['l', 'e']<\/p>\n\n\n\n<p>Now that we have seen enough of meta-characters, we will see how some of the methods of re module work. First, let us start with re.compile<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"re-compile\">re.compile<\/h4>\n\n\n\n<p>We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it. Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\npattern=re.compile('&#91;A-Z]&#91;a-z]+')\nresult=pattern.findall('Great Learning is all about excellence')\nprint(result)<\/code><\/pre>\n\n\n\n<p>Output: <\/p>\n\n\n\n<p>['Great',&nbsp;'Learning'] <\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"re-search\">re.search<\/h4>\n\n\n\n<p>The re.search function searches the string for a match and returns a Match object if there is a match. If there is more than one match, only the first occurrence of the match will be returned. Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\ntxt = \"The rain in Spain\"\nprint(re.search(\"Spain\", txt))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>&lt;_sre.SRE_Match object; span=(12, 17), match='Spain'&gt; <\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"re-split\">re.split<\/h4>\n\n\n\n<p>The re.split function returns a list where the string has been split at each match:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\ns_nums = 'one1two22three333four'\nprint(re.split('\\d+', s_nums))<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>['one', 'two', 'three', 'four']<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"re-sub\">re.sub<\/h4>\n\n\n\n<p>The re.sub function replaces the matches with the text of your choice<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\ns = 'aaa@xxx.com bbb@yyy.com ccc@zzz.com'\nprint(re.sub('&#91;a-z]*@', 'XXX@', s))<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">XXX@xxx.com XXX@yyy.com XXX@zzz.com<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"re-subn\">re.subn<\/h4>\n\n\n\n<p>As mentioned earlier, re.subn function is similar to re.sub function but it returns a tuple of 2 items containing the new string and the number of substitutions made.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\ns = 'aaa@xxx.com bbb@yyy.com ccc@zzz.com'\nprint(re.subn('&#91;a-z]*@', 'XXX@', s))<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"> ('XXX@xxx.com&nbsp;XXX@yyy.com&nbsp;XXX@zzz.com',&nbsp;3) <\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"re-match\">re.match<\/h4>\n\n\n\n<p>re.match function will search the regular expression pattern and return the first occurrence. This method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object. But if a match is found in some other line, it returns null. Here is an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re \nString ='''learning regex with \n           great learning is easy \n           also regex is very useful for string matching. \n           It is fast too.'''\n  \n# Use of re.search() Method \nprint(re.search('learning', String)) \n# Use of re.match() Method \nprint(re.match('learning', String)) \n# Use of re.search() Method \nprint(re.search('great learning', String)) \n# Use of re.match() Method \nprint(re.match('great learning', String)) <\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>&lt;_sre.SRE_Match&nbsp;object;&nbsp;span(0,&nbsp;8),&nbsp;match='learning'&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;_sre.SRE_Match&nbsp;object;&nbsp;span(0,&nbsp;8),&nbsp;match='learning'&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;_sre.SRE_Match&nbsp;object;&nbsp;span(32,&nbsp;46),&nbsp;match='great&nbsp;learning'&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; None&nbsp;&nbsp; <\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"re-group\">re.group<\/h4>\n\n\n\n<p>The re.group function returns entire match (or specific subgroup num).We can mention subgroups in Regular expression if we enclose them in parentheses.Here is an example to make it clear<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\nstring = \"Dogs are more loyal than cats\"\nmatchObj = re.match( r'(.*) are (.*?) .*', string)\nprint (\"matchObj.group() : \", matchObj.group(0))\nprint (\"matchObj.group(1) : \", matchObj.group(1))\nprint (\"matchObj.group(2) : \", matchObj.group(2))\n<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>matchObj.group()&nbsp;:&nbsp;&nbsp;Dogs&nbsp;are&nbsp;more&nbsp;loyal&nbsp;than&nbsp;cats&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; matchObj.group(1)&nbsp;:&nbsp;&nbsp;Dogs&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; matchObj.group(2)&nbsp;:&nbsp;&nbsp;more&nbsp; <\/p>\n\n\n\n<p>We define a group in Regular expression by enclosing them in parenthesis. As you can see we have defined two groups in the above Regular Expression, one is before are and another is after it. Thus in group 1, we have dogs and in group 2 we have more.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"regular-expression-program-in-python\"><strong>Regular Expression program in Python<\/strong><\/h2>\n\n\n\n<p>Now that we have seen how to use different RE, we are going to use them to write certain programs. So let us first write a program that can validate email id.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"email-validation-in-python-using-regular-expression\"><strong>Email Validation in Python using Regular Expression<\/strong><\/h3>\n\n\n\n<p>This program is going to take in different email ids and check if the given email id is valid or not. First, we will find patterns in different email id and then depending on that we design a RE that can identify emails. Now let us take look at some valid emails:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>dani123@gmail.com<\/li>\n\n\n\n<li>mysite@ourearth.com<\/li>\n\n\n\n<li>my.ownsite@ourearth.org<\/li>\n\n\n\n<li>mysite@you.me.net<\/li>\n\n\n\n<li>rahimrar@jkbnet.in<\/li>\n<\/ul>\n\n\n\n<p>Now let us take look at some examples of invalid email id:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>mysite.ourearth.com [@ is not present]<\/li>\n\n\n\n<li>mysite@.com.my [ tld (Top Level domain) can not start with dot \".\" ]<\/li>\n\n\n\n<li>@you.me.net [ No character before @ ]<\/li>\n\n\n\n<li>mysite123@gmail.b [ \".b\" is not a valid tld ]<\/li>\n\n\n\n<li>mysite@.org.org [ tld can not start with dot \".\" ]<\/li>\n\n\n\n<li>.mysite@mysite.org [ an email should not be start with \".\" ]<\/li>\n\n\n\n<li>mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ]<\/li>\n\n\n\n<li>mysite..1234@yahoo.com [double dots are not allowed]<\/li>\n<\/ul>\n\n\n\n<p>From the above examples we are able to find these patterns in the email id:<\/p>\n\n\n\n<p>The personal_info part contains the following ASCII characters.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Uppercase (A-Z) and lowercase (a-z) English letters.<\/li>\n\n\n\n<li>Digits (0-9).<\/li>\n\n\n\n<li>Characters ! # $ % &amp; ' * + - \/ = ? ^ _ ` { | } ~<\/li>\n\n\n\n<li>Character. ( period, dot or full stop) provided that it is not the first or last character and it will not come one after the other.<\/li>\n<\/ol>\n\n\n\n<p>The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.<br>Finally here is the program that can validate email ids using Regular Expressions<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\ndef validate_email(email):\n    if(re.search(r'\\b&#91;a-zA-Z0-9._%+-]+@&#91;a-zA-Z0-9.-]+\\.&#91;a-zA-Z]{2,}\\b',email)):  \n        print(\"Valid Email\")  \n          \n    else:  \n        print(\"Invalid Email\")\nvalidate_email(\"dani123@gmail.com\")\nvalidate_email(\"dani123gmail.com.in\")<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>Valid&nbsp;Email  <br>Invalid&nbsp;Email&nbsp; <\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"validate-mobile-number-using-regular-expression-in-python\"><strong>Validate mobile number using Regular Expression in Python<\/strong><\/h3>\n\n\n\n<p>In this section, we are going to validate the phone numbers. As the format of phone numbers can vary, we are going to make a program that can identify such numbers:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>+91-1234-567-890<\/li>\n\n\n\n<li> +911234567890<\/li>\n\n\n\n<li> +911234-567890<\/li>\n\n\n\n<li> 01234567890<\/li>\n\n\n\n<li> 01234-567890<\/li>\n\n\n\n<li> 1234-567-890<\/li>\n\n\n\n<li> 1234567890<\/li>\n<\/ul>\n\n\n\n<p>Here we can see a number can have a prefix of +91 0r 0. Also, there can be dashes after the first four digits of the number, and then after every 3 digit. You can try to find more patterns if they exist and then write your own regular expression.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\ndef validate_number(number):\n    if(re.search(r'^\\+91-?\\d{4}-?\\d{3}-?\\d{3}$|^0?\\d{4}-?\\d{3}-?\\d{3}$',number)):  \n        print(\"Valid Number\")  \n          \n    else:  \n        print(\"Invalid Number\")\nvalidate_number(\"+91-1234-567-890\")\nvalidate_number(\"+911234567890\")\nvalidate_number(\"+911234-567890\")\nvalidate_number(\"01234567890\")\nvalidate_number(\"01234-567890\")\nvalidate_number(\"1234-567-890\")\nvalidate_number(\"1234567890\")\nvalidate_number(\"12344567890\")\nvalidate_number(\"123-4456-7890\")<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<p>Valid Number<br>Valid Number<br>Valid Number<br>Valid Number<br>Valid Number<br>Valid Number<br>Valid Number<br>Invalid Number<br>Invalid Number<\/p>\n\n\n\n<p>Our <a href=\"https:\/\/www.mygreatlearning.com\/academy\" target=\"_blank\" rel=\"noreferrer noopener\">free online courses<\/a> are customized to suit individuals like you. Enhance your career prospects with sought-after domains like Data Science, Digital Marketing, Cybersecurity, Management, Artificial Intelligence, Cloud Computing, IT, and Software. These courses have been meticulously crafted by industry experts to equip you with hands-on experience and practical knowledge. Whether you're a novice seeking to embark on a new career path or a seasoned professional looking to upskill, our courses provide a flexible and easily accessible learning approach.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Regular Expression(regex or RE for short) as the name suggests is an expression which contains a sequence of characters that define a search pattern. Take an example of this simple Regular Expression : \\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b This expression can be used to find all the possible emails in a large corpus of text. This is useful because [&hellip;]<\/p>\n","protected":false},"author":41,"featured_media":20099,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[25860],"tags":[36796],"content_type":[],"class_list":["post-20050","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-software","tag-python"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Introduction to Regular Expression in Python (Regex)<\/title>\n<meta name=\"description\" content=\"Regular Expressions in Python contains a sequence of characters that define a search pattern. Let&#039;s discuss the same.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Introduction to Regular Expression in Python | Regex in Python\" \/>\n<meta property=\"og:description\" content=\"Regular Expressions in Python contains a sequence of characters that define a search pattern. Let&#039;s discuss the same.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"Great Learning Blog: Free Resources what Matters to shape your Career!\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/GreatLearningOfficial\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-18T17:23:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-18T12:49:28+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1000\" \/>\n\t<meta property=\"og:image:height\" content=\"750\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Great Learning Editorial Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/Great_Learning\" \/>\n<meta name=\"twitter:site\" content=\"@Great_Learning\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Great Learning Editorial Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/\"},\"author\":{\"name\":\"Great Learning Editorial Team\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\"},\"headline\":\"Introduction to Regular Expression in Python | Regex in Python\",\"datePublished\":\"2022-09-18T17:23:00+00:00\",\"dateModified\":\"2024-11-18T12:49:28+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/\"},\"wordCount\":2204,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/09\\\/shutterstock_278037536.jpg\",\"keywords\":[\"python\"],\"articleSection\":[\"IT\\\/Software Development\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/\",\"name\":\"Introduction to Regular Expression in Python (Regex)\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/09\\\/shutterstock_278037536.jpg\",\"datePublished\":\"2022-09-18T17:23:00+00:00\",\"dateModified\":\"2024-11-18T12:49:28+00:00\",\"description\":\"Regular Expressions in Python contains a sequence of characters that define a search pattern. Let's discuss the same.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/09\\\/shutterstock_278037536.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/09\\\/shutterstock_278037536.jpg\",\"width\":1000,\"height\":750,\"caption\":\"Regular Expression\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/regular-expression-in-python\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Blog\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"IT\\\/Software Development\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/software\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Introduction to Regular Expression in Python | Regex in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"name\":\"Great Learning Blog\",\"description\":\"Learn, Upskill &amp; Career Development Guide and Resources\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"alternateName\":\"Great Learning\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\",\"name\":\"Great Learning\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"width\":900,\"height\":900,\"caption\":\"Great Learning\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/GreatLearningOfficial\\\/\",\"https:\\\/\\\/x.com\\\/Great_Learning\",\"https:\\\/\\\/www.instagram.com\\\/greatlearningofficial\\\/\",\"https:\\\/\\\/www.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/in.pinterest.com\\\/greatlearning12\\\/\",\"https:\\\/\\\/www.youtube.com\\\/user\\\/beaconelearning\\\/\"],\"description\":\"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.\",\"email\":\"info@mygreatlearning.com\",\"legalName\":\"Great Learning Education Services Pvt. Ltd\",\"foundingDate\":\"2013-11-29\",\"numberOfEmployees\":{\"@type\":\"QuantitativeValue\",\"minValue\":\"1001\",\"maxValue\":\"5000\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\",\"name\":\"Great Learning Editorial Team\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"caption\":\"Great Learning Editorial Team\"},\"description\":\"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.\",\"sameAs\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/\",\"https:\\\/\\\/in.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/Great_Learning\",\"https:\\\/\\\/www.youtube.com\\\/channel\\\/UCObs0kLIrDjX2LLSybqNaEA\"],\"award\":[\"Best EdTech Company of the Year 2024\",\"Education Economictimes Outstanding Education\\\/Edtech Solution Provider of the Year 2024\",\"Leading E-learning Platform 2024\"],\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/author\\\/greatlearning\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Introduction to Regular Expression in Python (Regex)","description":"Regular Expressions in Python contains a sequence of characters that define a search pattern. Let's discuss the same.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Introduction to Regular Expression in Python | Regex in Python","og_description":"Regular Expressions in Python contains a sequence of characters that define a search pattern. Let's discuss the same.","og_url":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/","og_site_name":"Great Learning Blog: Free Resources what Matters to shape your Career!","article_publisher":"https:\/\/www.facebook.com\/GreatLearningOfficial\/","article_published_time":"2022-09-18T17:23:00+00:00","article_modified_time":"2024-11-18T12:49:28+00:00","og_image":[{"width":1000,"height":750,"url":"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg","type":"image\/jpeg"}],"author":"Great Learning Editorial Team","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/Great_Learning","twitter_site":"@Great_Learning","twitter_misc":{"Written by":"Great Learning Editorial Team","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#article","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/"},"author":{"name":"Great Learning Editorial Team","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad"},"headline":"Introduction to Regular Expression in Python | Regex in Python","datePublished":"2022-09-18T17:23:00+00:00","dateModified":"2024-11-18T12:49:28+00:00","mainEntityOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/"},"wordCount":2204,"commentCount":0,"publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg","keywords":["python"],"articleSection":["IT\/Software Development"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/","url":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/","name":"Introduction to Regular Expression in Python (Regex)","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#primaryimage"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg","datePublished":"2022-09-18T17:23:00+00:00","dateModified":"2024-11-18T12:49:28+00:00","description":"Regular Expressions in Python contains a sequence of characters that define a search pattern. Let's discuss the same.","breadcrumb":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#primaryimage","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg","width":1000,"height":750,"caption":"Regular Expression"},{"@type":"BreadcrumbList","@id":"https:\/\/www.mygreatlearning.com\/blog\/regular-expression-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog","item":"https:\/\/www.mygreatlearning.com\/blog\/"},{"@type":"ListItem","position":2,"name":"IT\/Software Development","item":"https:\/\/www.mygreatlearning.com\/blog\/software\/"},{"@type":"ListItem","position":3,"name":"Introduction to Regular Expression in Python | Regex in Python"}]},{"@type":"WebSite","@id":"https:\/\/www.mygreatlearning.com\/blog\/#website","url":"https:\/\/www.mygreatlearning.com\/blog\/","name":"Great Learning Blog","description":"Learn, Upskill &amp; Career Development Guide and Resources","publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"alternateName":"Great Learning","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.mygreatlearning.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization","name":"Great Learning","url":"https:\/\/www.mygreatlearning.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","width":900,"height":900,"caption":"Great Learning"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/GreatLearningOfficial\/","https:\/\/x.com\/Great_Learning","https:\/\/www.instagram.com\/greatlearningofficial\/","https:\/\/www.linkedin.com\/school\/great-learning\/","https:\/\/in.pinterest.com\/greatlearning12\/","https:\/\/www.youtube.com\/user\/beaconelearning\/"],"description":"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.","email":"info@mygreatlearning.com","legalName":"Great Learning Education Services Pvt. Ltd","foundingDate":"2013-11-29","numberOfEmployees":{"@type":"QuantitativeValue","minValue":"1001","maxValue":"5000"}},{"@type":"Person","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad","name":"Great Learning Editorial Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","caption":"Great Learning Editorial Team"},"description":"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.","sameAs":["https:\/\/www.mygreatlearning.com\/","https:\/\/in.linkedin.com\/school\/great-learning\/","https:\/\/x.com\/https:\/\/twitter.com\/Great_Learning","https:\/\/www.youtube.com\/channel\/UCObs0kLIrDjX2LLSybqNaEA"],"award":["Best EdTech Company of the Year 2024","Education Economictimes Outstanding Education\/Edtech Solution Provider of the Year 2024","Leading E-learning Platform 2024"],"url":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"}]}},"uagb_featured_image_src":{"full":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg",1000,750,false],"thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536-150x150.jpg",150,150,true],"medium":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536-300x225.jpg",300,225,true],"medium_large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536-768x576.jpg",768,576,true],"large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg",1000,750,false],"1536x1536":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg",1000,750,false],"2048x2048":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg",1000,750,false],"web-stories-poster-portrait":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg",640,480,false],"web-stories-publisher-logo":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg",96,72,false],"web-stories-thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/09\/shutterstock_278037536.jpg",150,113,false]},"uagb_author_info":{"display_name":"Great Learning Editorial Team","author_link":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"},"uagb_comment_info":0,"uagb_excerpt":"Regular Expression(regex or RE for short) as the name suggests is an expression which contains a sequence of characters that define a search pattern. Take an example of this simple Regular Expression : \\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b This expression can be used to find all the possible emails in a large corpus of text. This is useful because&hellip;","_links":{"self":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/20050","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/users\/41"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/comments?post=20050"}],"version-history":[{"count":19,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/20050\/revisions"}],"predecessor-version":[{"id":101634,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/20050\/revisions\/101634"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media\/20099"}],"wp:attachment":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media?parent=20050"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/categories?post=20050"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/tags?post=20050"},{"taxonomy":"content_type","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/content_type?post=20050"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}