-1

I need to get the values inside a string from an input form to use in a search, i will some examples:

Example 1: name="Peter Nash","Costa", should return Peter Nash and Costa.
Example 2: name='Peter Nash',"Costa", should return: Peter Nash and Costa.
Example 3: name="Peter Nash", should return: Peter Nash.
Example 4: name=Peter,"Costa", should return: Peter and Costa.
Example 5: name=Peter,Costa, should return: Peter and Costa.
Example 6: name=Peter, should return: Peter.

The name is a variable, it can change.

Right now i'm using something like new RegExp(string_var + "\:([^ ]+)", "").exec(input);, but doesn't work with quotes or commas.

Justin Grant
  • 44,807
  • 15
  • 124
  • 208
cpatricio
  • 457
  • 1
  • 5
  • 11
  • Your examples (name="string1","string2")are not valid JS. Please provide some code. – Randy Casburn Jun 03 '18 at 00:46
  • @RandyCasburn those are the inputs, but if you want as JS code, it would be like `var s = "name=\"Peter Nash\",\"Costa\"";` – cpatricio Jun 03 '18 at 01:19
  • Once you know how to extract the part after `name=`, you can take apply the `CSVtoArray` function on it by ridgerunner from https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data, demo based on your example input is here: https://codepen.io/anon/pen/QxjXrr?editors=0011 – Rico Chen Jun 03 '18 at 02:56
  • Was any of the answers helpful to you? – wp78de Jun 06 '18 at 15:34

3 Answers3

0

The regex:

(?!^name=)("|')?(?<first_name>([A-z]|\s)*)("|')*(\,{0,1})("|')*(?<second_name>(([A-z]|\s)*))("|')*$

https://regex101.com/r/3gKo9M/1

Code Sample:

let s = [
  "name=\"Peter Nash\",\"Costa\"",
  "name=\"Peter Nash\",\"Costa\"",
  "name='Peter Nash',\"Costa\"",
  "name=\"Peter Nash\"",
  "name=Peter,\"Costa\"",
  "name=Peter,Costa",
  "name=Peter",
];

const regex = /(?!^name=)("|')?(?<first_name>([A-z]|\s)*)("|')*(\,{0,1})("|')*(?<second_name>(([A-z]|\s)*))("|')*$/;

s.forEach(function(input){

   let regexResult = regex.exec(input);
   let output = regexResult["groups"]["first_name"];

   if(regexResult["groups"]["second_name"]!=""){
      output += ' AND ' + regexResult["groups"]["second_name"];
   }
   console.log(output);
});
Tiago Souza
  • 182
  • 1
  • 10
0

At its core, your sample text is comma-separated with optional quotes and can be treated like that. Thus, a .split regex is the right hammer for this problem. The only exception from a regular format is your variable-name prefix. The following split pattern does the heavy-lifting:

name=|,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)

Since you do not want to have the var name in the output, I am going to .filter it out. Also, quotes are removed using .replace on each element via .map.

Code Sample: Finally, everything wrapped up in a nice function:

function splitString(stringToSplit, separator) {
  var arr = stringToSplit.split(separator)
                         .map(str => str.replace(/^["']|["']$/g, ``)) //remove surrounding quotes
                         .filter(Boolean); //filter zero length results

  console.log('The array has ' + arr.length + ' elements: ' + arr.join(' and '));
}

const comma = /name=|,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/gm;

splitString(`name="Peter Nash","Costa"`, comma);
splitString(`name='Peter Nash',"Costa"`, comma);
splitString(`name="Peter Nash"`, comma);
splitString(`name=Peter,"Costa"`, comma);
splitString(`name=Peter,Costa`, comma);
splitString(`name=Peter`, comma);
wp78de
  • 18,207
  • 7
  • 43
  • 71
0

What you also might do is to split the string by name= and take the second part which will be a comma separated list. Then you could use a regex to capture 3 groups and use a backreference in the third group (\1) to make sure that the starting quote has the same closing quote.

Then use replace with the second group \$2

let pattern = /^(["'])(.*)(\1)$/;

If you would also allow "Costa' you could leave out the backreference and replace the pattern with:

let pattern = /^(["'])(.*)(['"])$/;

let pattern = /^(["'])(.*)(\1)$/;
const strings = [
  "name=\"Peter Nash\",\"Costa\"",
  "name=\"Peter Nash\",\"Costa\"",
  "name='Peter Nash',\"Costa\"",
  "name=\"Peter Nash\"",
  "name=Peter,\"Costa\"",
  "name=Peter,Costa",
  "name=Peter",
  "test",
  "test,",
  "name=   ",
  "name=\"Peter' test \" Nash\",\"Costa\"",
  "name='Peter Nash\",\"Costa'"
];
strings.forEach((str) => {
  let spl = str.split("name=");
  if (spl.length === 2 && spl[1].trim() !== "") {
    let result = spl[1].split(",").map(s => s.replace(pattern, "$2"));
    console.log(str + " ==> " + result.join(" and "));
  }

});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70