【问题标题】:Is it possible to use 'and' in re.search? [duplicate]是否可以在 re.search 中使用“和”? [复制]
【发布时间】:2017-09-24 21:45:31
【问题描述】:

我需要在每一行中搜索多个单词,如果一行中的所有单词都匹配,则打印该行。

文件.txt

This is starting string.
This is starting but different string.
This is starting but the same string.
This is a differnet string.
This is a old string.

我已经按照以下方式完成了。

import re
with open("file.txt", "r") as in_file:
    for line in in_file:
        if (re.search('different',line)) and (re.search('string',line)):
            print line

但我需要类似的东西:

if (re.search('different' and 'string',line))::
            print line

我知道我们有或我们正在使用

if (re.search('different'|'string',line))::
                print line

谁能帮助我以类似的方式使用“和”。

【问题讨论】:

  • 你为什么要使用正则表达式? all(w in line for w in ('different', 'string')) 也可以。否则:不,没有“和”正则表达式选项。
  • 从副本中:re.search(r'(?=.*different)(?=.*string)', line) 也适用于大小写。
  • @martijn-pieters:谢谢你只记得基础知识。

标签: python regex python-2.7


【解决方案1】:

您不需要在这里使用模块rein 操作员将为您完成这项工作。

if 'different' in line and 'string' in line:

【讨论】:

  • 谢谢。我对此有想法,这就是为什么我在正则表达式中也尝试了相同的方法并添加到我的帖子中。无论如何 all(x in line for x in ['different', 'string']) 已经完成了我的工作。再次感谢您。
【解决方案2】:

在您的情况下,不需要使用正则表达式,您可以使用 'string' in line and 'different' in lineall(x in line for x in ['different', 'string'])

【讨论】:

  • 非常感谢。我无法添加 +1,但谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多