首页 > 解决方案 > 如何只匹配一次出现双空格的行?

问题描述

A线

foo bar  bar foo  bar foo

B线

foo bar  bar foo

A 行中,有多次出现双倍空格。

我只想匹配只有一次双空格出现的B 行这样的行。

我试过了

^.*\s{2}.*$

但它会匹配两者。

我怎样才能获得所需的输出?谢谢你。

标签: python-3.xregex

解决方案


如果您希望匹配包含不超过一个字符串且单词之间有两个或多个空格的字符串,您可以使用以下正则表达式。

r'^(?!(?:.*(?<! ) {2,}(?! )){2})'

启动你的引擎!

请注意,此表达式匹配

abc    de fgh

'c'其中和之间有四个空格'd'

Python 的正则表达式引擎执行以下操作。

^
(?!           : begin negative lookahead
  (?:         : begin non-capture group
    .*        : match 0+ characters other than line terminators
    (?<!      : begin negative lookbehind
      [ ]{2,} : match 2+ spaces
      (?! )   : negative lookahead asserts match is not followed by a space
    )         : end negative lookbehind
  )           : end non-capture group
  {2}         : execute non-capture group twice
)             : end negative lookahead

推荐阅读