【问题标题】:JS Regex: (a|b) Matches the a or the b part of the subexpression. Different behaviour when a and b switched [duplicate]JS Regex: (a|b) 匹配子表达式的 a 或 b 部分。 a和b切换时的不同行为[重复]
【发布时间】:2019-03-09 20:31:38
【问题描述】:

我正在尝试使用正则表达式概念将 2% 替换为 ''(empty)。如果输入字符串是 %2%,则应将其替换为 ''(empty):

const str = "2%";

console.log(`2%`.replace(/^\d%$|\d(?=%)/, ''));
console.log(`2%`.replace(/\d(?=%)|^\d%$/, ''));

(a|b) Matches the a or the b part of the subexpression.

"2%".replace(/^\d%$|\d(?=%)/, '')。这很好用。

但是,"2%".replace(/\d(?=%)|^\d%$/, '') 没有。

【问题讨论】:

  • 那么您的问题和问题是什么?您似乎有有效的源代码....
  • | 的左侧匹配,所以这就是替换的内容。到底有什么令人惊讶的地方?
  • @Pointy,它像短路运算符一样工作吗?
  • 是的,第一个匹配“wins”的选项。

标签: javascript regex


【解决方案1】:

区别在于正则表达式首先尝试匹配的内容。左边的表达式优先。仅在左侧匹配失败时才尝试右侧。

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2011-10-20
    • 2014-03-29
    • 2012-11-12
    • 2015-06-12
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多