【问题标题】:How to do negate search using regex in Python?如何在 Python 中使用正则表达式进行否定搜索?
【发布时间】:2021-01-27 19:30:39
【问题描述】:
re.search('python', 'Working on python is easy')

在这里我可以搜索python。

我想放置负模式,实际上应该没有结果或不匹配。

我喜欢在字符串包含 python 但不包含 easy 的字符串“Working on python is easy”时使用 re.search。我该怎么做?正面和负面条件同时出现。

【问题讨论】:

  • 这可能会有所帮助 - stackoverflow.com/questions/406230/…
  • not re.search(...) 有什么问题?
  • 我喜欢使用 re.search,当字符串包含 python 但字符串中不包含 easy 'Working on python is easy'。我该怎么做?正面和负面条件同时出现。

标签: python-3.x regex


【解决方案1】:

您可以使用 if statement 以便匹配 object 仅在未给出 easy 时返回 True

例如:

import re
if re.search('python', 'Working on python is easy') and not re.search('easy', 'Working on python is easy'):
    print("found a match")

一些其他来源可能对您有所帮助:

Python: How to use RegEx in an if statement?

https://docs.python.org/3/library/re.html#match-objects

How to use RegEx in an if statement in Python?

【讨论】:

  • 谢谢。但我不想要 if 条件,因为我会有模式列表。有些只有肯定搜索,有些可能有肯定搜索和否定搜索,也可以有多个字符串要搜索而不是搜索。所以如果条件我认为,不会工作。
  • 我认为它会,你可能不得不把它放在你的问题中,而不是更精确一点。它可以与列表结合使用。但是现在请说明您的问题
猜你喜欢
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 2014-10-21
  • 2020-10-04
相关资源
最近更新 更多