HomePagev2 Forums Python Discussions Regular Expressions Reply To: Regular Expressions

  • Sai Gowtham Babu AMBURI Gowtham Babu AMBURI

    October 5, 2020 at 4:59 pm

    Python has a built-in package called re, which can be used to work with Regular Expressions.

    When you have imported the re module, you can start using regular expressions:


    To see if it starts with “The” and ends with “Spain”:

    import re

    txt = "The rain in Spain"
    x = re.search("^The.*Spain$", txt)

    if x:
        print("YES! We have a match!")
        print("No match")
    the output is going to be YES! We have a match!

    since we have the characters present in the code

    RegEx Functions

    The re module offers a set of functions that allows us to search a string for a match:

    Function Description
    findall Returns a list containing all matches
    search Returns a Match objectif there is a match anywhere in the string
    split Returns a list where the string has been split at each match
    sub Replaces one or many matches with a string


    Metacharacters are characters with a special meaning:

    Character Description Example
    [] A set of characters “[a-m]”
    \ Signals a special sequence (can also be used to escape special characters) “\d”
    . Any character (except newline character) “he..o”
    ^ Starts with “^hello”
    $ Ends with “world$”
    * Zero or more occurrences “aix*”
    + One or more occurrences “aix+”
    {} Exactly the specified number of occurrences “al{2}”
    | Either or “falls|stays”
    () Capture and group

    I hope you understood about how regular expressions can be used. Try to use a condition so that you can know whether the elements are present in a given string or not.

    I have preferred to think link below to explain about RE. There are many other examples in the following Link below.
    It would be more helpful.
    Thank you .