Skip to main content
 首页 » 编程设计

Python 正则表达式;让 0 匹配 0 或 1

2025年05月04日10daizhj

我有一个较短的字符串 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')