python-3.x - 如何只匹配一次出现双空格的行?
问题描述
A线
foo bar bar foo bar foo
B线
foo bar bar foo
在A 行中,有多次出现双倍空格。
我只想匹配只有一次双空格出现的B 行这样的行。
我试过了
^.*\s{2}.*$
但它会匹配两者。
我怎样才能获得所需的输出?谢谢你。
解决方案
如果您希望匹配包含不超过一个字符串且单词之间有两个或多个空格的字符串,您可以使用以下正则表达式。
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
推荐阅读
- python - 为什么我的逻辑回归预测为 0 或 1
- azure - Azure Functions 存储帐户网络安全
- html - app.facebook.com 身份验证过程中的 Safari X-Frame-Options DENY 错误
- reactjs - 如何在 setTimeout 后修复 setState
- google-bigquery - 安排查询以在 BigQuery 中的项目之间复制数据集中的数据
- python - 在 C++ 中加载和使用使用 LSTM 网络构建的 Keras 模型或在 iOS 应用程序中部署该模型
- rest - 如何使用 jersey 在现有的 JSF 应用程序中集成休息服务?
- macos - 在 Mac 上的真实移动设备上查看 .NET Core 项目
- python - Python程序给出n值并使用for循环计算n+nn+nnn的值
- flutter - 在 AppBar 和 TabBarView 下设置高度