DEV Community

Cover image for Python RegEx Tutorial with practice
Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

Python RegEx Tutorial with practice

Hi Friends,
Today one of the important topics for programming is RegEx.
For python regular expression we are learning from (W3schools Python RegEx Tutorial)[https://www.w3schools.com/python/python_regex.asp]

Start
for python RegEx, we have to import the RegEx module by
import re
and we can see the output

import re
print(re)
Enter fullscreen mode Exit fullscreen mode

Example 1

txt = "Hello World, Hello Bangladesh"
result = txt.replace('Bangladesh', "India")
print(result)
Enter fullscreen mode Exit fullscreen mode

our variable is "txt" and "result" variable is making the RegEx and replace Bangladesh to India
.
Search
RegEx search way

Example 2

import re

txt = "The rain in Spain"
result = re.search('Spain', txt)
if result:
    print("Span is there")
else:
    print("Span is not there")

Enter fullscreen mode Exit fullscreen mode

we have made a condition if "txt" variable has "Spain" string the condition will be true else false.

The re module offers below the function

  • findall
  • search
  • split
  • sub

Also,
there are few Metacharacters we will see some example of how the RegEx working here.

  • [] = set. example "[a-m]"
  • \ = special sequence. example "[\d]"
  • . = aspect new line. example "he..o"
  • ^ = start position. example "^hello"
  • $ = end position. example "world$"
  • * = zero or more occurrences. example "aix*"
  • + = one or more sequance. example "aix+"
  • {} = specific number. example "al{2}"
  • | = either or. example "hello|world"
  • () = capture and group. example "(world)"

we can see more details and w3schools but for this post, we are going to show some examples for more details we will follow w3schools.

Example

import re

txt = "I love mango"
result = re.findall("o", txt) # output ["o", "o"]

print(result)
Enter fullscreen mode Exit fullscreen mode

you see the findall python method working like "g" global javascript method.

split method

import re

txt = "I love mango Oh"
result = re.split("O", txt)

print(result)
Enter fullscreen mode Exit fullscreen mode

split method separates the string to an array first it searches where the letter match then separates with the array.
The above example output ['I love mango ', 'h']

This is our short tutorial, we will not go deeply just the basic concept of every tutorial.
After we master the basic things then we will go deep things.
If you like this short tutorial please like, comment. thanks all guys.

Discussion (0)