python - 未能捕获第一个词组
问题描述
我正在尝试为以下可能的情况编写正则表达式。我用re.finditer()
withre.IGNORECASE
来匹配字符串。可能的情况和相应的匹配是
'vessel eta: 12-10-19'
应该匹配'vessel eta: '
'vessel eta 12-10-19'
应该匹配'vessel eta '
'etd eta : 12/10/19'
应该匹配'etd eta '
'eta SIN: 12/10/19'
应该匹配'eta SIN:'
'eta : 12-10-19
应该匹配'eta :'
'eta: 12-10-19'
应该匹配'eta: '
'eta. 12-10-19'
应该匹配'eta. '
'eta 12-10-19'
应该匹配'eta '
直到现在,我写了这个:
((vessel)|(ETD))?(\s\.\:)?(ETA)[\s\.\:]{1,3}?(SIN)?[\s\.\:]?
但是根据regex101,这与除了前三种情况之外的所有情况都匹配,其中第一个单词(无论是'vessel'
还是'etd'
)都没有被捕获。
我的正则表达式有什么问题?
解决方案
The (\s\.\:)?
pattern matches an optional sequence of a whitespace, a dot and then a colon, while you want to match a single optional character, a whtespace, .
or :
.
Note you overescape chars in the character class: [.]
always matches a dot and :
is not a special regex metacharacter.
It is advisable to use non-capturing groups ((?:...)
) if you do not need to further access parts of the regex matches, or just remove the grouping parentheses altogether when they do not contain alternatives or are not quantified.
You may use
(?:vessel|ETD)?[\s.:]?ETA[\s.:]{1,3}?(?:SIN)?[\s.:]?
See the regex demo.
推荐阅读
- python - 有没有办法让 tkinter 中的滚动条更长?
- phpmyadmin - phpmyadmin 列标题在浏览表格时重复更多次
- c++ - 即使使用 extern 和 #ifdef 也已在 .obj 中定义
- firebase - CircleCI 权限拒绝为 Firebase 部署打开 firebase-tools.json
- swift - Swift/MapKit - 注释相互重叠
- android - Android actionbar自定义不变色
- python - 将 XML 文件解析为 CSV 而不对值进行硬编码
- objective-c - 应用程序:启动画面后未调用 OpenFile
- sql - SQL:使用 REGEXP_REPLACE 删除表的另一列中的部分字符串
- javascript - xhttp.open 节点模块的路径