**************************************************
Python Core PlayList : • Lesson - 01 : Python3 - What is python
Python Advanced PlayList : • Lesson - 46 : Python Advanced - Pytho...
**************************************************
Python REGEX:
Regular expression is widely used for pattern matching. Python has built-in support for regular function. To use regular expression you need to import re module.
import re
Now you are ready to use regular expression.
re.search() Method : re.search() is used to find the first match for the pattern in the string.
Syntax: re.search(pattern, string, flags[optional])
re.search() method accepts pattern and string and returns a match object on success orNone if no match is found. match object has group() method which contains the matching text in the string.
All the special character and escape sequences loose their special meanings in raw string so\n is not a newline character, it’s just backslash \ followed by n .
>>> import re
>>> s = "my number is 123"
>>> match = re.search(r'\d\d\d', s)
>>> match
<_sre.SRE_Match object; span=(13, 16), match='123'>
>>> match.group()
'123'
Basic patterns used in regular expression:
Symbol Description
. dot matches any character except newline
\w matches any word character i.e letters, alphanumeric, digits and underscore ( _ )
\W matches non word characters
\d matches a single digit
\D matches a single character that is not a digit
\s matches any white-spaces character like \n, \t, spaces
\S matches single non white space character
[abc] matches single character in the set i.e either match a, b or c
[^abc] match a single character other than a, b and c
[a-z] match a single character in the range a to z.
[a-zA-Z] match a single character in the range a-z or A-Z
[0-9] match a single character in the range 0-9
^ match start at beginning of the string
$ match start at end of the string
+ matches one or more of the preceding character (greedy match).
* matches zero or more of the preceding character (greedy match).
Group capturing
Group capturing allows to extract parts from the matching string. You can create groups using parentheses () . Suppose we want to extract username and host name from the email address in the above example. To do this we need to add () around username and host name like this.
match = re.search(r'([\w.-]+)@([\w.-]+)', s)
Optional flags
Both re.search() and re.findall() accepts and optional parameter called flags. flags are used to modify the behavior of the pattern matching.
Sample Projects : https://github.com/SadaLearningHub1/P...