gpt4 book ai didi

javascript - 将 css 选择器与 RegExp 匹配在浏览器中不起作用

转载 作者:行者123 更新时间:2023-11-30 00:05:44 27 4
gpt4 key购买 nike

我尝试匹配 css 选择器,如下所示: https://regex101.com/r/kI3rW9/1.它根据需要匹配测试字符串,但是当加载 .js 文件以在浏览器中对其进行测试时,它在 firefox 和 chrome 中均失败。


.js 文件:

window.onload = function() {
main();
}
main = function() {
var regexSel = new RegExp('([\.|#][a-zA-Z][a-zA-Z0-9.:_-]*) ?','g');
var text = "#left_nav .buildings #rfgerf .rtrgrgwr .rtwett.ww-w .tw:ffwwwe";
console.log(regexSel.exec(text));
}

在浏览器中返回:["#left_nav ", "#left_nav", index: 0, input: "#left_nav .buildings #rfgerf .rtrgrgwr .rtwett.ww-w .tw:ffwwe"]

所以看起来它只捕获第一个有和没有空格的选择器,尽管空格在 () 和全局标志集之外。

编辑:因此,循环 RegExp.exec(text) 或仅使用 String.match(str) 将导致正确的解决方案。感谢 Wiktor 的回答,我能够实现一种调用此功能的便捷方式:

function Selector(str){
this.str = str;
}
with(Selector.prototype = new String()){
toString = valueOf = function () {
return this.str;
};
}

Selector.prototype.constructor = Selector;
Selector.prototype.parse = function() {
return this.match(/([\.|#][a-zA-Z][a-zA-Z0-9.:_-]*) ?/g);
}
//Using it the following way:
var text = new Selector("#left_nav .buildings #rfgerf .rtrgrgwr .rtwett.ww-w .tw:ffwwwe");
console.log(text.parse());

不过我决定使用/([\.|#][a-zA-Z][a-zA-Z0-9.:_-]*) ?/g over the suggested

/([.#][a-zA-Z][a-zA-Z0-9.:_-]*)(?!\S)/g 因为它匹配在我的测试字符串上,regex101.com 上的 44 步与 60 步。

最佳答案

你运行了一次exec,所以你得到了一个匹配对象。您需要在循环内运行它。

var regexSel = new RegExp('([\.|#][a-zA-Z][a-zA-Z0-9.:_-]*) ?','g');
var text = "#left_nav .buildings #rfgerf .rtrgrgwr .rtwett.ww-w .tw:ffwwwe";
while((m=regexSel.exec(text)) !== null) {
console.log(m[1]);
}

末尾带有 (?!\S) 环视的正则表达式(如果在主要消费模式后没有非空白,则匹配失败)将允许更简单的代码:

var text = "#left_nav .buildings #rfgerf .rtrgrgwr .rtwett.ww-w .tw:ffwwwe";
console.log(text.match(/[.#][a-zA-Z][a-zA-Z0-9.:_-]*(?!\S)/g));

请注意,在定义 static 正则表达式时,您应该考虑使用正则表达式文字表示法。只有当您的模式是动态、有一些您不想转义的变量或太多/ 时,才更喜欢使用RegExp 的构造函数符号。

另请参阅 [.#]:点不必转义,| 内部被视为文字管道符号(不是交替运算符)。

关于javascript - 将 css 选择器与 RegExp 匹配在浏览器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38616901/

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