gpt4 book ai didi

javascript - 创建所有正则表达式匹配的数组?

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:54 24 4
gpt4 key购买 nike

我正在尝试使用 package match-all匹配 CSS 选择器并返回所有选择器的数组。这是代码。

const matchAll = require("match-all");

let s = `.u-br, .u-nr {
blah blah
}

.u-tr {
blah .blah
}`;
console.log(matchAll(s, /\.-?[_a-zA-Z]+[\w-]*(?=[^{}]*\{)/g).toArray());

当我运行它时,它只记录 [],但正则表达式是正确的 as can be seen here .

想法?如果包有错误,是否有简单的解决方法?

最佳答案

作为documentation显示:

let s = "Hello _World_ and _Mars_";
console.log(matchAll(s, /_([a-z]+)_/gi).toArray());
// => [ "World", "Mars" ]

结果数组由捕获组构建。这就是他们所有的例子所表明的。据推测,如果您没有捕获组,您可以使用内置的 .match 实现相同的效果:

let s = `.u-br, .u-nr {
blah blah
}

.u-tr {
blah .blah
}`;
console.log(s.match(/\.-?[_a-zA-Z]+[\w-]*(?=[^{}]*\{)/g));

因此,如果您想为此使用 match-all,请尝试将匹配项包含在捕获组中:

matchAll(s, /(\.-?[_a-zA-Z]+[\w-]*(?=[^{}]*\{))/g).toArray()

关于javascript - 创建所有正则表达式匹配的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com