简体   繁体   中英

Regex match all excluding a delimiter

I have two sample strings of code like so:

"const x = anything;"
"const {a, b, c, d} = anything;"

I want to match x , as well as a , b , c , and d (none of which are literal, they can be any valid JavaScript variable character(s), but are delimited by commas) if they are preceded by the keyword const . The latter is the destructuring syntax.

Context: this is to extend syntax highlighting of code tokens in PrismJS.

What I've tried so far:

  Prism.languages.insertBefore(lang, 'operator', {
    constant: {
      pattern: /(const\s?{?)[\s_$a-zA-Z\xA0-\uFFFF,]*(?!:)/,
      lookbehind: true,
    },
  });

The comma is inside the [] , and I am not sure of how to "continue" matching each variable inside the braces without including the comma character.

Try this pattern:

(?:const\s+{?\s*)[_$\w]+(?:[,}\s])

I'll try and improve it by replacing \\w to match identifiers using non-alphanumeric characters. Possibly:

(?:const\s+{?\s*)[_$\p{L}]+(?:[,}\s])

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