首页 > 解决方案 > 未能捕获第一个词组

问题描述

我正在尝试为以下可能的情况编写正则表达式。我用re.finditer()withre.IGNORECASE来匹配字符串。可能的情况和相应的匹配是

  1. 'vessel eta: 12-10-19'应该匹配'vessel eta: '
  2. 'vessel eta 12-10-19'应该匹配'vessel eta '
  3. 'etd eta : 12/10/19'应该匹配'etd eta '
  4. 'eta SIN: 12/10/19'应该匹配'eta SIN:'
  5. 'eta : 12-10-19应该匹配'eta :'
  6. 'eta: 12-10-19'应该匹配'eta: '
  7. 'eta. 12-10-19'应该匹配'eta. '
  8. 'eta 12-10-19'应该匹配'eta '

直到现在,我写了这个:

((vessel)|(ETD))?(\s\.\:)?(ETA)[\s\.\:]{1,3}?(SIN)?[\s\.\:]?

但是根据regex101,这与除了前三种情况之外的所有情况都匹配,其中第一个单词(无论是'vessel'还是'etd')都没有被捕获。

我的正则表达式有什么问题?

标签: pythonregexpython-3.x

解决方案


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.


推荐阅读