Suppose I have a string of characters.
charstr = "SZR"
Suppose that the character Z is a loaded character and can represent S, P, Q, W, or R
I want to write a function get_regex(charstr) which takes charstr as an input and returns a regular expression string. Which can then be used to find patterns in other strings.
The following code should not results in answer = 'None', since SZR matches SRR and SWR, which are in SQSRRSWR.
charstr = "SZR"
answer = re.search(get_regex(charstr), 'SQSRRSWR')
I have tried the following but it won't work. Any suggestions?
import re
def get_regex(charstr):
charstr = re.sub("Z", "[SPQWR]{1}", charstr) # Z: can be S,P,Q,W, or R
#The line directly below this was in my original post. I have commmented it out and the function now works properly.
#charstr = "\'\'\'^ " + charstr + "\'\'\'" # Results in '''^ S[SPQWR]{1}R'''
return charstr
charstr = "SZR"
answer = re.search(get_regex(charstr), 'SQSRRSWR')
print(answer) # Results in None
charstrto'''^ S[SPQWR]{1}R'''makes your regex work. Is there any significance to that part?^S[SPQWR]R, so why not just'^{}'.format(charstr)?