Skip to content Skip to sidebar Skip to footer

Javascript String Match Specific Regex

I want to match specific string from this variable. var string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64'; Here is my regex : var string = '150-50

Solution 1:

You may use ((?:\+|^)skip)? capturing group before (\d+(?:\s*[-*\/+]\s*\d+)*\s*=\s*\d+) in the pattern, find each match, and whenever Group 1 is not undefined, skip (or omit) that match, else, grab Group 2 value.

var string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64', 
 reg = /((?:^|\+)skip)?(\d+(?:\s*[-*\/+]\s*\d+)*\s*=\s*\d+)/gi,
 match_data = [], 
 m;
while(m=reg.exec(string)) {
   if (!m[1]) {
      match_data.push(m[2]);
   }
}
console.log(match_data);

Note that I added / and + operators ([-*\/+]) to the pattern.

Regex details

  • ((?:^|\+)skip)? - Group 1 (optional): 1 or 0 occurrences of +skip or skip at the start of a string
  • (\d+(?:\s*[-*\/+]\s*\d+)*\s*=\s*\d+) - Group 2:
    • \d+ - 1+ digits
    • (?:\s*[-*\/+]\s*\d+)* - zero or more repetitions of
      • \s*[-*\/+]\s* - -, *, /, + enclosed with 0+ whitespaces
      • \d+ - 1+ digits
    • \s*=\s* - = enclosed with 0+ whitespaces
    • \d+ - 1+ digits.

Solution 2:

As per your input string and the expected results in array, you can just split your string with + and then filter out strings starting with skip and get your intended matches in your array.

const s = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64'console.log(s.split(/\+/).filter(x => !x.startsWith("skip")))

There are other similar approaches using regex that I can suggest, but the approach mentioned above using split seems simple and good enough.

Solution 3:

try

var t = string.split('+skip');
var tt= t[1].split('+');
var r = [t[0],tt[1],tt[2]]

var string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64';

var t = string.split('+skip');
var tt= t[1].split('+');
var r = [t[0],tt[1],tt[2]]

console.log(r)

Solution 4:

const string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64';
const stepOne = string.replace(/skip[^=]*=\d+./g, "")
const stepTwo = stepOne.replace(/\+$/, "")
const result = stepTwo.split("+")
console.log(result)

Post a Comment for "Javascript String Match Specific Regex"