regex - 我可以创建条件查找并用正则表达式替换吗?

标签 regex nginx

我正在尝试使用允许使用正则表达式的 NginX 替换过滤器。我可以让它以基本方式工作,即将 phone 替换为 telephone,但我似乎无法让它有条件地替换一串文本。

这里是检查 XML 的检查:

eat apples cantaloupe bananas often

我想执行以下规则集:

  1. 寻找以 eat 开头并以 often 结尾的字符串
  2. 如果字符串包含bananas,则将bananas替换为尤其是bananas
  3. 如果字符串不包含bananas,则不对字符串做任何操作

我知道我可以使用类似这样的东西来使部分字符串可用:

/(eat.*)(bananas)?(.*often)/

假设 bananas 存在,我可以使用以下规则进行替换:

   $1 and especially $2 $3

但如果 bananas 不存在,这将给出一个奇怪的结果:

输入

eat apples cantaloupe often

输出:

eat apples cantaloupe and especially often

我需要前瞻运算符吗?我读过 this article但我还是遇到了麻烦。

最佳答案

尝试使用前瞻:

/(?=.*eat.*bananas.*often) bananas/

关于regex - 我可以创建条件查找并用正则表达式替换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14449560/

相关文章:

javascript - 正则表达式限制与特定表达式的完全匹配

c# - 用 c# 中的 2 个换行符替换 1 个换行符

python - 使用 Nginx throttle 服务器脚本

php - Symfony 与 nginx 不提供 .js 和 .css 文件

nginx - 如何在 nginx Web 服务器的重写规则中将大写字母转换为小写字母?

regex - 提取 Haskell 中特定类型的所有出现

Java - 使用组的正则表达式

nginx - 在 nginx 反向代理后面运行的 Kubernetes Ingress

nginx - 通过 nginx 入口 Controller 进行基本身份验证

python - 如何创建包含变量和注释的正则表达式?