简体   繁体   English

如何在javascript中使用正则表达式选择不在双/单引号之间的数字

[英]how to select numbers that is not between double/single quotes with regular expression in javascript

hi i have problem selecting the numbers that is not in the single/double qoutes . 嗨我有问题选择不在单/双qoutes中的数字。 let say we have this text below . 假设我们在下面有这个文本。

    <style color='#424242'></style>

123

    /* you can count this 5454 */

    <style color="#767676"></style>

8787

i want to select just the 123 and 8787 , nothing else how should i do this with regular expression in javascript 我想只选择123和8787,没有别的我应该如何使用javascript中的正则表达式

if i use \\d in RegExp it w'll select all the numbers and i know that . 如果我在RegExp中使用\\ d,它将选择所有数字,我知道。 but i want to tell it that only select those numbers that is not surrounded by double/single/star . 但我想告诉它只选择那些没有被双/单/星包围的数字。

I would do that : 我会这样做:

var numbers = str.split('"').filter(function(_,i){ return !(i%2) }).join('')
                 .split("'").filter(function(_,i){ return !(i%2) }).join('')
                 .match(/\d+/g);

The idea is to start by removing what is between quotes and then applying a regular expression. 我们的想法是首先删除引号之间的内容,然后应用正则表达式。

Demonstration (open the console) 演示 (打开控制台)

But, like any time HTML and regexes are mixed, you'll find cases where it doesn't work. 但是,就像HTML和正则表达式混合在一起时,你会发现它不起作用的情况。 So, if your use case isn't strictly controlled, you'd better parse, for example by applying a regex to element.texContent||element.innerText . 因此,如果您的用例没有严格控制,您最好解析,例如将正则表达式应用于element.texContent||element.innerText

This is probably not very cross-browser solution: 这可能不是非常跨浏览器的解决方案:

var iterator = document.evaluate(
    "descendant::text()",
    document.body, null,
    XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null),
node;
while (node = iterator.iterateNext()) {
    (node.nodeValue.match(/\d+/) || []).forEach(console.log);
}

Tested only in Firefox, but AFAIK, most browsers provide some XPath API, just look into the relevant documentation. 仅在Firefox中测试,但AFAIK,大多数浏览器都提供了一些XPath API,只需查看相关文档即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM