【问题标题】:Matching comma after certain phrase在某些短语后匹配逗号
【发布时间】:2019-09-05 06:31:25
【问题描述】:

我使用的是 Atom 的正则表达式搜索和替换功能,而不是 JavaScript 代码。

我认为这个兼容 JavaScript 的正则表达式可以工作(我想匹配后面有 Or rather 的逗号):

(?!\b(Or rather)\b),
  • ?! = 负前瞻

  • \b = 字边界

  • (...) = 搜索整个单词,而不是逐个字符

  • \b = 字边界

  • , = 实际字符。

但是,如果我从“或更确切地说”中删除字符,则正则表达式仍然匹配。我很困惑。

https://regexr.com/4keju

【问题讨论】:

  • 您是要在逗号前匹配Or rather,还是在逗号前其他而不是Or rather
  • @TimBiegeleisen 我正在尝试匹配逗号。后面有Or rather 的任何逗号。
  • (?:or rather)(,)
  • I want to match the commas that have Or rather behind it 但在模式中你使用的是消极的后视
  • @alexchenco 你可以在原子read this thread中使用lookbehind@

标签: regex atom-editor


【解决方案1】:

您可能打算使用积极的lookbehind而不是消极的lookbehind

(?<=\b(Or rather)\b),

Regex Demo

您可以使用标志在 atom 中激活 lookbehind Read this thread

【讨论】:

    【解决方案2】:

    (?!\b(Or rather)\b), 模式等于 ,,因为 , 不等于 O,因此负前瞻总是返回 true。

    要删除 AtomOr rather 之后的逗号,请使用

    查找内容\b(Or rather),
    替换为$1

    确保选择 .* 选项以启用正则表达式(Aa 用于区分大小写交换)。

    \b(Or rather), 匹配

    • \b - 单词边界
    • (Or rather) - 捕获组 1,匹配 Or rather 文本并将其保存在内存缓冲区中,可以在替换模式中使用 $1 进行访问
    • , - 逗号。

    JS 正则表达式演示:

    var s = "Or rather, an image.\nor rather, an image.\nor rather, friends.\nor rather, an image---\nOr rather, another time they.";
    console.log(s.replace(/\b(Or rather),/g, '$1'));
    // Case insensitive:
    console.log(s.replace(/\b(Or rather),/gi, '$1'));

    【讨论】:

    • 感谢您的回答。有没有办法在不依赖$1 的情况下匹配,?我使用的是 Atom 的正则表达式搜索和替换功能,而不是 JavaScript 代码。
    • @alexchenco 好吧,我认为 Atom 中的唯一方法就是我在答案中显示的内容。
    【解决方案3】:

    要匹配“或者更确切地说”之后的任何逗号,您可以简单地使用 (或者更确切地说)(,)并使用 match[2] 访问第二组

    或者另一种方法是使用或作为非捕获组 (?:or rather)(,) 所以第一组在“Or rather”之后是逗号

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2011-06-02
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      相关资源
      最近更新 更多