My QA Projects

QA Projects I was involded.

View on GitHub

How to Compile Regular Expressions

Regex Performance

Precompiling Regex

Using the Regex Module

=> import re odule => compile regular expression pattern => get pattern object => call search methods from pattenr object with string

Pattern Object Methods

re.compile(pattern, flags=0)

# compile a regex pattern and returns a patter object
# takes optional flags

Search Method

pattern_object.search(string, start, stop)

# return a match object if the pattern_object is found in string
# return None if not found
# start and stop are opttional indexes for the search range in string

Match Method

pattern_object.match(string, start, stop)

# return a match object if the pattern_object is found at the  beginnign of a  string
# return None if not found
# start and stop are opttional indexes for the search range in string

Find All Method

pattern_object.findall(string, start, stop)

# return a list of substring in string that match the pattern_object
# return None if not found
# start and stop are opttional indexes for the search range in string

Precompilation Example

import re
s = 'software hardware'
pattern= re.compile('ware') # creating a pattern object 
match = pattern.search(s)
 if match:
    print("matched")
    # Output matched

Let’s test

# test_regex.py
import unittest
import re

class TestRegexMatch(unittest.TestCase):

    def test_match_found(self):
        s = 'software hardware'
        pattern = re.compile('ware')
        match = pattern.search(s)
        self.assertIsNotNone(match, "Match should be found")

    def test_match_not_found(self):
        s = 'hello world'
        pattern = re.compile('ware')
        match = pattern.search(s)
        self.assertIsNone(match, "Match should not be found")

if __name__ == '__main__':
    unittest.main()

run test with

python -m unittest test_regex.py

Test Class

Test Methods:

Running the Tests: