Home > Net >  NOT selecting between quotes: Regex, Javascript
NOT selecting between quotes: Regex, Javascript

Time:04-18

I want to only match numbers that are not immediately adjacent to a letter AND not in between any pair of ['"`] quotes or backticks.

the first part is easy,

(?<![a-zA-Z])\d (?![a-zA-Z])

however Im having difficulty with the second part, this is where I am right now.

(?![^`"']*['"`])

Currently this regex is only selecting qualified numbers after the first set of backticks (both 70's) in the following string:

for (let i8 = 1; i <= 10; i ) { console.log("Pass numb60er ${8}")70; }70

I appreciate your help and time.

CodePudding user response:

One approach would be to match using the following regex pattern:

[`"'].*?[`"']|\b\d \b

This will first try to match any quoted term, and that failing will try to match a standalone number. Then, we can filter off the quoted terms from the resulting array leaving behind only the matching numbers.

var input = "for (let i8 = 1; i <= 10; i  ) { console.log(`Pass numb60er ${8}`)70; }70";
var nums = input.match(/[`"'].*?[`"']|\b\d \b/g);
nums = nums.filter(x => !x.match(/[`"'].*[`"']/));
console.log(nums);

CodePudding user response:

Try this: /(?<=[^a-zA-Z'"`])\d (?=[^a-zA-Z'"`])/gm

let s = 'for (let i8 = 1; i <= 10; i  ) { console.log("Pass `21` numb60er ${8}")70; }70'

let pattern = /(?<=[^a-zA-Z'"`])\d (?=[^a-zA-Z'"`])/gm

console.log(s.match(pattern))
//[[ "1", "10", "8", "70", "7" ]

This will match only those numbers which are not adjacent to letters or surrounded by any type of quotes.

  • Related