![](/img/trans.png)
[英]python regular expression: match either one of several regular expressions
[英]Python Regular Expressions; Having 0 match either 0 or 1
我有一個較短的字符串s
我試圖匹配一個較長的字符串s1.
1匹配1,但0匹配0或1。
例如:
s = '11111' would match s1 = '11111'
s = '11010' would match s1 = '11111' or '11011' or '11110' or '11010'
我知道正則表達式將使這一過程變得容易得多,但對從何處開始感到困惑。
將每個0
實例替換為[01]
以使其與0
或1
匹配:
s = '11010'
pattern = s.replace('0', '[01]')
regex = re.compile(pattern)
regex.match('11111')
regex.match('11011')
在我看來,您實際上正在尋找位運算
s = '11010'
n = int(s, 2)
for r in ('11111', '11011', '11110', '11010'):
if int(r, 2) & n == n:
print r, 'matches', s
else:
print r, 'doesnt match', s
import re
def matches(pat, s):
p = re.compile(pat.replace('0', '[01]') + '$')
return p.match(s) is not None
print matches('11111', '11111')
print matches('11111', '11011')
print matches('11010', '11111')
print matches('11010', '11011')
您說“與更長的字符串s1匹配”,但是您沒有說是要匹配字符串的開頭還是結尾等。在我更好地理解您的要求之前,這將執行完全匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.