【问题标题】:regex that matches a literal that doesn't have another literal before it [duplicate]与之前没有其他文字的文字匹配的正则表达式[重复]
【发布时间】:2019-07-05 17:56:19
【问题描述】:

所以我有一个要求,我想用== 替换字符串中的所有=,但问题是字符串也可能包含!=,我不想要= 或@987654326 @ 将被替代。 所以仅仅用==替换=是行不通的,我在想是否有一种方法可以检查=在替换之前是否没有!。 我四处寻找正则表达式,但这似乎并没有解决问题。

【问题讨论】:

  • 了解look-behinds
  • 您的示例 I/O?
  • 如果你只是想替换==,那么连续替换两个equals会有什么问题呢?
  • 重复问题。
  • (?<!!)= 应该让你得到前面没有!的等号

标签: python regex regex-lookarounds


【解决方案1】:

使用replace

test = "Hey this is a == test where != or = should not be changed"
print(test.replace("==", "="))

输出:

Hey this is a = test where != or = should not be changed

import re
replaced = re.sub('==', '=', test)
print(replaced)

编辑:

你需要的是:

(?<!a)b matches a "b" that is not preceded by an "a",

= 的正则表达式,其中= 前面没有=

test = "Hey this is a = test where != or = should not be changed"

import re
print(re.findall(r'(?<!!)=', test))

【讨论】:

  • 编辑了我的修复答案,downvoter 现在可能想删除他的downvote?
猜你喜欢
  • 1970-01-01
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多