我们可以使用以下正则表达式来匹配符合要求的字符串:
^[a-zA-Z0-9]{5,7}( [a-zA-Z0-9]{1,2})?$
这个正则表达式做的事情是:
示例代码:
import re
regex = r'^[a-zA-Z0-9]{5,7}( [a-zA-Z0-9]{1,2})?$'
test_str = 'abcde'
print(bool(re.match(regex, test_str))) # 输出 True
test_str = 'abcdef'
print(bool(re.match(regex, test_str))) # 输出 True
test_str = 'abcdefg'
print(bool(re.match(regex, test_str))) # 输出 True
test_str = 'abcdehijkl'
print(bool(re.match(regex, test_str))) # 输出 False
test_str = 'ab abcd'
print(bool(re.match(regex, test_str))) # 输出 True
test_str = 'ab abcde'
print(bool(re.match(regex, test_str))) # 输出 False
test_str = 'ab abcd '
print(bool(re.match