假设我有一个字符串。你知道吗
charstr = "SZR"
假设字符Z是加载的字符,可以表示S、p、Q、W或R
我想写一个函数getregex(charstr),它将charstr作为输入并返回一个正则表达式字符串。 然后可以用来在其他字符串中查找模式。你知道吗
以下代码不应导致answer='None',因为SZR与SRR和SWR匹配,后者在sqsrwr中。你知道吗
charstr = "SZR"
answer = re.search(get_regex(charstr), 'SQSRRSWR')
我试过下列方法,但不起作用。有什么建议吗?你知道吗
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
你的例子似乎很接近实际。如果我明白你想做什么,这是可行的:
结果:
这看起来正是你想要做的。我去掉了{1},因为这是隐含的。如果你觉得不对劲,就发表评论,我会更新你的答案。你知道吗
相关问题 更多 >
编程相关推荐