要编写一个类似于CA123456SDL或CA123456的模式的正则表达式,可以使用以下代码示例:
import re
pattern = r'CA\d{6}(SDL)?'
test_strings = ['CA123456', 'CA456789SDL', 'CA987654']
for test_string in test_strings:
match = re.match(pattern, test_string)
if match:
print(f'{test_string} 匹配成功')
else:
print(f'{test_string} 匹配失败')
运行以上代码,输出结果会显示每个测试字符串是否匹配模式。正则表达式CA\d{6}(SDL)?
用于匹配以"CA"开头,后面跟着6个数字,然后可选地以"SDL"结尾的字符串。