Python:String到Regex模式

2024-09-28 05:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个字符串。你知道吗

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

Tags: 函数字符串answerinrenonesearchget
1条回答
网友
1楼 · 发布于 2024-09-28 05:25:40

你的例子似乎很接近实际。如果我明白你想做什么,这是可行的:

import re

def get_regex(charstr):
    charstr = re.sub("Z", "[SPQWR]", charstr) # Z: can be S,P,Q,W, or R
    return charstr

charstr = "SZR"
if re.search(get_regex(charstr), 'SQSRRSWR'):
    print("yep it matched")
else:
    print("nope it does not match")

charstr = "SXR"
if re.search(get_regex(charstr), 'SQSRRSWR'):
    print("yep it matched")
else:
    print("nope it does not match")

结果:

yep it matched
nope it does not match

这看起来正是你想要做的。我去掉了{1},因为这是隐含的。如果你觉得不对劲,就发表评论,我会更新你的答案。你知道吗

相关问题 更多 >

    热门问题