Reputation:
I have the following code which matches the string in comments variable,how do I construct the string that matches for both the comments shown below?I want to check for QSPR TEST RESULTS:\siggy.* and TEST RESULTS:.*
import re
comments = "QSPR TEST RESULTS:\\siggy\QSPRLog\QCA\CST\2016\3\28\TestCaseLogs\N12345678-3_28_16_16_36_29_000_635947797916487681.html are the results"
#comments = "TEST RESULTS:BT ON\OFF LOOKS GOOD"
def matchcomments(comments, matchstring):
matchobj = re.search(matchstring, str(comments))
if matchobj:
return True
return False
def main ():
try:
string = r"QSPR TEST RESULTS:\\siggy\.*"
match = matchcomments(comments, string)
if match == True:
tested_bit_flag = True
else:
#string = r"Included in BIT"
string = r"DONOT MATCH"
match = matchcomments(comments, string)
if match == True:
tested_bit_flag = True
else:
tested_bit_flag = False
except KeyError:
tested_bit_flag = False
print "This gerrit does not have comments:"
print tested_bit_flag
if __name__ == "__main__":
main()
Upvotes: 1
Views: 433
Reputation: 1240
comments = "QSPR TEST RESULTS:\\siggy\QSPRLog\QCA\CST\2016\3\28\TestCaseLogs\N12345678-3_28_16_16_36_29_000_635947797916487681.html are the results"
string = r"(?:QSPR)?\s?TEST\sRESULTS:\\siggy\\(.*)|(?:DONOT MATCH)"
matchobj = re.search(string, comments)
if matchobj:
print True
print matchobj.group(1) #Gives you the text you are interested in eg. QSPRLog\QCA\CST\2016\3\28\TestCaseLogs\N12345678-3_28_16_16_36_29_000_635947797916487681.html are the results
else:
print False
Explanation:
(?:QSPR)? and (?:DONOT MATCH)
(?:) indicates a non-capturing group. The idea is to check presence or absence of the group (in this case QSPR or DONOT MATCH) without caring what the match is (since we already know what it is). A question mark at the end indicates that that group is optional.
\s?TEST\sRESULTS:\siggy\
This part just matches the text pretty much as given.
(.*)
Captures the text you are interested in in a group. Note that this is the only (capturing) group so when you call the match object's group attribute with parameter 1, you get the text you are interested in.
Also note that this regex would capture 0 or more characters. Replace with (.+) to capture 1 or more characters so as to ensure non-emptiness.
The | character indicates that either the expression on the left or the one on the right should match. In this particular case, since there are no groups in the expression on the right (?:DONOT MATCH), calling matchobj.group(1) when comments="DONOT MATCH" would return None. Make sure to check for this later in the code.
Upvotes: 1
Reputation: 1640
If I understood you correctly:
^(?:QSPR )?TEST RESULTS:.+$
This should match the text you are interested in.
Upvotes: 0
Reputation: 17
string = r"(QSPR TEST RESULTS:\\siggy\.*)|(DONOT MATCH)"
use this.
Upvotes: 0