[英]Python: String to Regex Pattern
假設我有一串字符。
charstr = "SZR"
假設字符Z是已加載的字符,並且可以表示S,P,Q,W或R
我想編寫一個函數get_regex(charstr),將charstr作為輸入並返回一個正則表達式字符串。 然后可以用來查找其他字符串中的模式。
由於SZR與SQSRRSWR中的SRR和SWR匹配,因此以下代碼不應導致答案=“無”。
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
您的示例似乎非常有效。 如果我了解您要執行的操作,則可以這樣做:
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}。 只是在評論不對時扔掉評論,我將更新此答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.