data.match(var)似乎不起作用

data.match(var) not working it seems

本文关键字:不起作用 var match data      更新时间:2023-09-26

好的,所以我有一小段代码,它应该扫描网站上的数字,但出于某种原因,我有一种预感,它根本没有扫描。

var Regex = /'<span class="currency-robux" data-se="item-privatesale-price">(['d,]+)'<'/span'>/;
                    var PriceSelling = data.match(Regex);
                    PriceSelling = Number(PriceSelling.replace("," , ""));

我在这上面的东西有什么问题吗?

这连接到if语句

if (PriceSelling <= PriceWanting) {

它从那里调用一个函数来运行,但由于某种原因,它似乎从未运行过。所以我认为Regex是错误的,但不确定是怎么错的。(PriceWanting有一个变量;这只是代码本身的一个片段。)

在网站上,这是我试图提取的内容。

<span class="robux " data-se="item-privatesale-price">115</span>

请记住,item-privatesale-price发生了变化,这就是为什么我将其设置为捕获该数据。

您的regex通常很好,但您使用的结果是错误的。如果匹配,它将返回一个包含完整字符串和匹配数字的结果。不仅仅是数字。您只需要数字,即匹配索引1,就可以使用PriceSelling[1]

此外,在您的编辑中,您正在将spanclass="robux "进行匹配,这显然与您的正则表达式不同。如果你只是对data-se="item-privatesale-price"感兴趣,你可以将其更改为匹配其中具有该属性的标签

var data = '<span class="robux " data-se="item-privatesale-price">115</span>';
// matches a span with the data-se attribute within it
// i.e. appears before the closing >
var Regex = /'<span[^>]* data-se="item-privatesale-price"[^>]*>(['d,]+)'<'/span'>/;
var PriceSelling = 0;
var PriceSellingMatch = data.match(Regex);
if(PriceSellingMatch != null) {
    PriceSelling = Number(PriceSellingMatch[1].replace("," , ""));
}

正则表达式ex中的类是错误的,您正在查找:

/'<span class="currency-robux" data-se="item-privatesale-price">(['d,]+)'<'/span'>/

但是正则表达式应该是

/'<span class="robux " data-se="item-privatesale-price">(['d,]+)'<'/span'>/

查看类属性值的差异

Regex不适合解析HTML,您可以这样做:

var div = document.createElement("div");
div.innerHTML = YOUR_HTML_STRING;
var price = parseInt(div.querySelector("[data-se='item-privatesale-price']").innerHTML);
console.log(price);  // => 115

点击此处查看:JSFiddle