【问题标题】:Negative Look-ahead in Regex doesn't seem to be working正则表达式中的负前瞻似乎不起作用
【发布时间】:2019-04-05 19:59:34
【问题描述】:

我正在尝试使用 Regex 从遵循严格模式的 url 中提取子域。我只想匹配 与指定的子域 的 url,所以我使用的是否定的前瞻。这似乎适用于许多正则表达式评估器,但是当我在节点中运行时,两个字符串都会匹配。代码如下:

const defaultDomain = 'https://xyz.domain.com';
const scopedDomain = 'https://xyz.subdomain.domain.com';

const regex = /^https:\/\/xyz\.([^.]+(?!domain))\./
const matchPrefix1 = defaultDomain.match(regex);
const matchPrefix2 = scopedDomain.match(regex);

console.log(matchPrefix1);
console.log(matchPrefix2);

预期: matchPrefix1 是 null,而 matchPrefix2 会导致第一个捕获组是“子域”的匹配项

实际: matchPrefix1 和 matchPrefix2 都包含数据,捕获组分别返回为“域”和“子域”

链接到正则表达式(有效!):https://regexr.com/42bfn

repl 链接(无效):https://repl.it/@tomismore/SpiffyFrivolousLaws

这是怎么回事?

【问题讨论】:

    标签: node.js regex negative-lookahead


    【解决方案1】:

    Regexr 显示您的代码工作正常,因为您没有添加多行标志。这会导致第二行的开头与^ 不匹配,因此忽略整个第二行。添加多行标志以查看您的正则表达式不起作用。

    我会使用这个正则表达式:

    ^https:\/\/xyz\.(?!domain)([^.]+)\.
    

    我所做的更改是在检查(?!domain) 之后将[^.]+ 部分移动到。基本上,您应该在匹配xyz\. 后立即检查(?!domain)

    【讨论】:

    • 太快了!谢谢!
    猜你喜欢
    • 2011-07-21
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2011-10-14
    • 2010-12-17
    • 1970-01-01
    相关资源
    最近更新 更多