Home > Software engineering >  How to split a string based on a regex pattern with conditions (JavaScript)
How to split a string based on a regex pattern with conditions (JavaScript)

Time:11-26

I am trying to split a string so that I can separate it depending on a pattern. I'm having trouble getting the correct regex pattern to do so. I also need to insert the results into an array of objects. Perhaps by using a regex pattern, the string can be split into a resulting array object to achieve the objective. Note that the regex pattern must not discriminate between - or --. Or is there any better way to do this?

I tried using string split() method, but to no avail. I am trying to achieve the result below:

const example1 = `--filename test_layer_123.png`;
const example2 = `--code 1 --level critical -info "This is some info"`;

const result1 = [{ name: "--filename", value: "test_layer_123.png" }];
const result2 = [
    { name: "--code", value: "1" },
    { name: "--level", value: "critical" },
    { name: "-info", value: "This is some info" },
];

CodePudding user response:

If you really want to use Regex to solve this.

Try this Pattern /((?:--|-)\w )\s "?([^-"] )"?/g

Code example:

function matchAllCommands(text, pattern){
  let new_array = [];
  let matches = text.matchAll(pattern);
  for (const match of matches){
    new_array.push({name: match.groups.name, value: match.groups.value});
  }
  return new_array;
}

let RegexPattern = /(?<name>(?:--|-)\w )\s "?(?<value>[^-"] )"?/g;
let text = '--code 1 --level critical -info "This is some info"';

console.log(matchAllCommands(text, RegexPattern));

CodePudding user response:

Here is a solution that splits the argument string using a positive lookahead, and creates the array of key & value pairs using a map:

function getArgs(str) {
  return str.split(/(?= --?\w  )/).map(str => {
    let m = str.match(/^ ?([^ ] ) (.*)$/);
    return {
      name: m[1],
      value: m[2].replace(/^"(.*)"$/, '$1')
    };
  });
}

[
  '--filename test_layer_123.png', // example1
  '--code 1 --level critical -info "This is some info"' // example2
].forEach(str => {
  var result = getArgs(str);
  console.log(JSON.stringify(result, null, ' '));
});

Positive lookahead regex for split:

  • (?= -- positive lookahead start
  • --?\w -- expect space, 1 or 2 dashes, 1 word chars, a space
  • ) -- positive lookahead end

Match regex in map:

  • ^ -- anchor at start of string
  • ? -- optional space
  • ([^ ] ) -- capture group 1: capture everything to next space
  • -- space
  • (.*) -- capture group 2: capture everything that's left
  • $ -- anchor at end of string
  • Related