Skip to content

Instantly share code, notes, and snippets.

@lhlyu
Created February 17, 2023 13:32
Show Gist options
  • Save lhlyu/88c2d1913d828d806d87630b254345f5 to your computer and use it in GitHub Desktop.
Save lhlyu/88c2d1913d828d806d87630b254345f5 to your computer and use it in GitHub Desktop.
记录一个python正则匹配的坑
import re
# 待匹配的字符串
s = '[AB=1231][AC=23] [AC=3,as=12]'
# 匹配的规则
rule = r'(\[AC\=\d+(,[a-z]+\=\S+)*\])'
# 结果: [('[AC=23]', ''), ('[AC=3,as=12]', ',as=12')]
print(re.findall(rule, s))
## 下面是一些教训总结
# re.match 只能匹配开头的子字符串
# re.search 只能匹配第一个出现的子字符串
# re.findall 如果不使用捕获组,它会返回 `['', ',as=12']`, 非重叠部分
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment