Built with Tutify.io

    AIStudyLabs

    Python regex tester

    Python regex tester

    Building your own regular expressions is pretty exciting but more so testing them if they are working as you intended them to. Python regex testers come in handy when you want to test and experiment with your regular expressions thus helping you to know the accuracy of your patterns.

    In this tutorial, you will learn how to build regex testers in Python, allowing you to validate and fine-tune your regular expressions effectively. We will walk through the process of creating a Python regex tester step by step, empowering you to gain a deeper understanding of regular expressions and their practical applications.

    Here is what you will learn at the end of this tutorial:

    <a id="h-what-is-a-python-regex-tester"></a>

    What is a Python regex tester?

    First things first, before you dive deep into building your regex testers, you have to understand what they are and what they are used for. A Python regex tester is simply a program that allows you to test and do experiments with your Python-built regular expressions. The main purpose why you would need a regex tester is that it helps you validate and fine-tune your regular expressions.

    <a id="h-features-of-a-python-regex-tester"></a>

    Features of a Python regex tester

    A Python regex tester that is well-built has these features as a bare minimum:

    | Feature | Description | | --- | --- | | Input fields | It allows you to enter the regular expression pattern you want to test and the text to apply the pattern to | | Matching results | After applying the regular expression pattern to the input text, the tester displays the matching results, showing any portions of the text that match the pattern | | Feedback on matches | The tester may provide feedback such as the total number of matches found and the specifically matched substrings or captured groups | | Flags and options | Some testers allow you to specify flags and options for the regular expression pattern e.g. case-insensitive matching or multiline matching | | Error handling | It may handle and display any errors or exceptions that occur during pattern matching |

    <a id="h-building-a-python-regex-tester"></a>

    Building a Python regex tester

    Now having looked at the features of a regex tester, you now get to understand how you will build one on your own. A regex tester is just a user-defined function that takes two parameters, a pattern, and the text:

    | Parameter | Description | | --- | --- | | pattern | The regular expression pattern that you want to test | | text | The input text that you want to apply the regular expression pattern to |

    The function syntax looks like this:

    
    def regex_tester(pattern, text):
        ...
    
        ...
    
        ...
    

    Note:

    Since this is a user-defined function, you can name it whatever you want, just make sure the name makes sense.

    <a id="h-examples-of-a-python-regex-tester"></a>

    Examples of a Python regex tester

    Now let us look at some practical examples of the Python regex tester, this will help you solidify your understanding. As the saying goes, the best way to learn code is to write code. So let us dive in!!!!

    <a id="h-finding-email-addresses"></a>

    Finding email addresses

    The first example will be to extract email addresses from a given text. Here is an example:

    
    import re
    
    def regex_tester(pattern, text):
        # find all matches of the given pattern in the text
        matches = re.findall(pattern, text)
        
        if matches:
            # if matches are found, print "Matches found:"
            print("Matches found:")
            
            # iterate over the matches and print each match
            for match in matches:
                print(match)
        else:
            # if no matches are found, print "No matches found."
            print("No matches found.")
    
    # example usage:
    pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
    # the pattern matches email addresses
    
    text = "Contact us at aistudylabs@gmail.com or info@aistudylabs.com for more information."
    
    # call the regex_tester function with the pattern and text as arguments
    regex_tester(pattern, text)
    

    In the code snippet, we define a function called regex_tester() that takes two parameters: pattern and text. The function uses the re.findall() method from the re module to find all matches of the given pattern in the text. And with the help of an if-else statement, we check if the matches are found or not and then iterate over the matches using a for loop.

    Finally, the regex_tester() function is then called with this pattern and a sample text that contains email addresses. The function applies the pattern to the text and displays any matches found.

    Output:

    
    #Output
    Matches found:
    aistudylabs@gmail.com
    info@aistudylabs.com
    

    <a id="h-extracting-phone-numbers"></a>

    Extracting phone numbers

    The second example will be to extract phone numbers from the text as follows:

    
    import re
    
    def regex_tester(pattern, text):
        # find all matches of the given pattern in the text
        matches = re.findall(pattern, text)
        
        if matches:
            # if matches are found, print "Matches found:"
            print("Matches found:")
            
            # iterate over the matches and print each match
            for match in matches:
                print(match)
        else:
            # if no matches are found, print "No matches found."
            print("No matches found.")
    
    # example usage:
    pattern = r'\d{3}-\d{3}-\d{4}'
    # the pattern matches phone numbers in the format xxx-xxx-xxxx
    
    text = "Please call 123-456-7890 to speak with AIStudyLabs customer support."
    
    # call the regex_tester function with the pattern and text as arguments
    regex_tester(pattern, text)
    

    A specific regular expression pattern is defined in the code snippet to match phone numbers in the format xxx-xxx-xxxx. The regex_tester() function is then called with this pattern and a sample text that contains a phone number. The function applies the pattern to the text and displays the matching phone number.

    Output:

    
    #Output
    Matches found:
    123-456-7890
    

    <a id="h-finding-dates"></a>

    Finding dates

    The final example is for finding dates:

    
    import re
    
    def regex_tester(pattern, text):
        # find all matches of the given pattern in the text
        matches = re.findall(pattern, text)
        
        if matches:
            # if matches are found, print "Matches found:"
            print("Matches found:")
            
            # iterate over the matches and print each match
            for match in matches:
                print(match)
        else:
            # if no matches are found, print "No matches found."
            print("No matches found.")
    
    # example usage:
    pattern = r'\d{2}/\d{2}/\d{4}'
    # the pattern matches dates in the format xx/xx/xxxx
    
    text = "The AIStudyLabs Data Science Bootcamp will take place on 12/25/2023. Don't miss it!"
    
    # call the regex_tester function with the pattern and text as arguments
    regex_tester(pattern, text)
    

    Similar to the above examples, this code also defines a function called regex_tester that takes two parameters: pattern and text. The function uses the re.findall() method from the re module to find all matches of the given pattern in the text. We have an if-else statement for checking whether the matches is True or False. If it’s True, iterate it using a for loop. Outside the function, we are creating the actual pattern and text and to use the function we are calling it with its respective parameters.

    Output:

    
    #Output
    Matches found:
    12/25/2023
    

    <a id="h-conclusion"></a>

    Conclusion

    That’s it from this tutorial, I hope you have learned so much about the Python regex testers and that the knowledge gained will be used in your future Python projects.