\(\renewcommand\AA{\unicode{x212B}}\)
string in file: 'email'
regex: 'email' # This is a regular expression but albeit not a very
# useful one as only matches with one word!
*
specifies that the character preceding it can
appear zero or more times, e.g,regex: 'a*b'
test: 'b' # Matches as there are no occurrences of 'a'
test: 'ab' # Matches as there is a single 'a'
test: 'aaaaaaaab' # Matches as there are multiple occurrences of 'a'
test: 'aaaabab' # Matches as there is an occurrence of a string of
# a's followed by a b
[]
, e.g.regex: '[a-z]'
test: 'm' # Matches as it is a lower case letter
test: 'M' # Fails as it is an upper case letter
test: '4' # Fails as it is a number
regex: '[a-z,A-Z,0-9]'
test: 'm' # Matches!
test: 'M' # Matches!
test: '4' # Matches!
test: 'mm' #Fails as there are two characters
regex: '[a-z,A-Z,0-9]*'
test: 'mm' # Matches
test: 'a0123' # Matches
{}
, e.g.regex: 'a{2}'
test: 'abab' # Fails as there is not two consecutive a's in the string
test: 'aaaab' # Matches
re
that
allows strings to be tested against regular expressions with a few
lines of code. Reference: http://docs.python.org/2/library/re.htmlcompile
function also takes another optional argument
controlling the matching process, all of which are documented at the
above location. Here we pass the RE.IGNORECASE
option meaning
that a case-insensitive match is performed.import re
def checkForMatch(checker, test):
if checker.match(test) != None:
print('String matches!')
else:
print('String does not contain a match')
# End of function definition
checker = re.compile('[a-z]')
checkForMatch(checker, 'a')
checkForMatch(checker, '9')
checker = re.compile('[a-z]', re.IGNORECASE)
checkForMatch(checker, 'a')
checkForMatch(checker, 'A')
Gives the output:
String matches!
String does not contain a match
String matches!
String matches!
Running 13 tests.............OK!
where the line has to start with the word ‘Running’ and end with the word ‘OK!’ or the test is considered a failure.
import re
filetestsRun = 'testResults.log'
f = open(filetestsRun,'r')
reTestCount = re.compile("Running\\s*(\\d+)\\s*test", re.IGNORECASE)
reCrashCount = re.compile("OK!")
reFailCount = re.compile("Failed\\s*(\\d+)\\s*of\\s*(\\d+)\\s*tests", re.IGNORECASE)
testCount = 0
failCount = 0
testsPass = True
for line in f.readlines():
m=reTestCount.search(line)
if m:
testCount += int(m.group(1))
m=reCrashCount.search(line)
if not m:
failCount += 1
testsPass = False
m=reFailCount.match(line)
if m:
# Need to decrement failCount because crashCount will
# have incremented it above
failCount -= 1
failCount += int(m.group(1))
testsPass = False
f.close()
print("Tests Passed: {}".format(testsPass))
print("Tests Failed: {}".format(failCount))
print("Total Tests: {}".format(testCount))