简体   繁体   中英

Create array of all regular expression matches?

I'm attempting to use the package match-all to match CSS selectors and return an array of all of them. This is the code.

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());

When I run it it just logs [] , but the regex is correct as can be seen here .

Thoughts? If the package has a bug, is there a simple work around?

As the documentation shows:

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

The resulting array is constructed from the capturing groups . This is what all their examples show. Presumably, if you don't have capturing groups, you could achieve the same thing using the built-in .match :

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

So, if you want to use match-all for this, try enclosing the match in a capturing group:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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