Home > other >  Javascript & regular expression
Javascript & regular expression

Time:12-27

I have this string

java=10514;js=237;jsp=3995;web=5;xml=42

and I'd like to extract, in separate variables, the value numbers for each language, using javascript and a regular expression that is, for the "java" case, the follow

(?<=java=).*?(?=;|$)

I've tried this code

var myString = "java=10514;js=237;jsp=3995;web=5;xml=42";
var regexp_java = new RegExp('(?<=java=).*?(?=;|$)', 'g');    
var ncloc_java = sonar_myString.match(regexp_java);
var regexp_js = new RegExp('(?<=js=).*?(?=;|$)', 'g');    
var ncloc_js = sonar_myString.match(regexp_js);
var regexp_jsp = new RegExp('(?<=jsp=).*?(?=;|$)', 'g');    
var ncloc_jsp = sonar_myString.match(regexp_jsp);
var regexp_web = new RegExp('(?<=web=).*?(?=;|$)', 'g');    
var ncloc_web = sonar_myString.match(regexp_web);
var regexp_jsp = new RegExp('(?<=jsp=).*?(?=;|$)', 'g');    
var ncloc_jsp = sonar_myString.match(regexp_jsp);

but it doesn't work.

Any suggestion will be appreciated and thank you in advance

CodePudding user response:

I believe that you are using the wrong data structure here. Rather than trying to use individual variables for each language, you can instead use a hashmap. First split to the string on semicolon, and then stream that to get each language and value.

var input = "java=10514;js=237;jsp=3995;web=5;xml=42";
var map = {};
input.split(";").forEach(x => map[x.split("=")[0]] = x.split("=")[1]);
console.log(map);

CodePudding user response:

Does it really need to be done with Regex? Anyways I'm providing you with 2 solutions.

const string = "java=10514;js=237;jsp=3995;web=5;xml=42";

let result1 = string.split(';').reduce((acc, curr) => {
  let [key, value] = curr.split('=');
  acc[key] = value;
  return acc;
}, {});

console.log(result1);

let result2 = {};
let regex = /([a-z] )\s*=\s*(\d )/g;
let check;

while (check= regex.exec(string)) {
  result2[check[1]] = check[2];
}

console.log(result2);

CodePudding user response:

You don't have to create separate patterns and variables, Instead you can use 2 capture groups and then create an object with keys and values (assuming there are no duplicate keys)

\b(java|jsp?|web|xml)=([^;\s] )

Explanation

  • \b A word boundary
  • (java|jsp?|web|xml) Match one of the alternatives
  • = Match literally
  • ([^;\s] ) Capture group 2, match 1 chars other than a whitespace char or ;

See a regex demo.

const myString = "java=10514;js=237;jsp=3995;web=5;xml=42";
const regex = /\b(java|jsp?|web|xml)=([^;\s] )/g;
const kv = Object.fromEntries(
  Array.from(
    myString.matchAll(regex), m => [m[1], m[2]]
  )
)
console.log(kv)
console.log(kv.java);

  • Related