Javascript Regex to capture variables in curved brackets

I have a string that is fed into a JavaScript function and I need to pull variables out of it.

var str = "heres:a:func('var1', 'var2', 'var3', 2)"

      

I am getting close, but would like to do it with one regex.

str.match(/\((.*)\)/)[1].split(/\s*,\s*/)

      

The results should look like this:

['var1', 'var2', 'var3', 2]

      

+3


source to share


4 answers


Here's one way to do it:

Regex101 reference

This doesn't include quotes, by the way, you can add them if you like.

var pattern = /(\w+)(?!.*\()(?=.*\))/g;
var str = "heres:a:func('var1', 'var2', 'var3', 2)";
var matches = str.match(pattern);
console.log(matches); //['var1','var2','var3','2']

      

It basically looks for a group of word characters and then makes a negative and positive result.
Basically

(?!.*\() 

      

says that I want it NOT to come before any number of plus characters (character and

(?=.*\)) 

      

says I WANT it to be before any number of characters and a) a character.

Then the capture group is at the beginning, so you can replace (\ w +) with ([\ '\ w] +) if you want to keep the quotes (which I don't think you are right)




Edit: To include spaces in your lines, you can do something like this:

var pattern = /([\w]+\s[\w]+|\w+)(?!.*\()(?=.*\))/g

      

But this will not capture trailing white space, just spaces surrounded by two types of words (a-Z0-1). Also, this will only allow 1 space in a word, so if you want multiples you will need to check that as well. You can change it to check for any number of word characters or spaces between two valid word characters.

For multiple spaces:

var pattern = /([\w]+[\s\w]*[\w]+|\w+)(?!.*\()(?=.*\))/g

      

Includes 1 Space: Link Regex101

Includes multiple spaces: Reference Regex101

Edit2:
And as the last one, if you REALLY want to add a bunch of spaces, you can do this:

Includes multiple spaces, multiple times: Reference Regex101

/([\w]+[\s\w]+[\w]+|\w+)(?!.*\()(?=.*\))/g

      

+1


source


In this case, ('\w+'|\d+)

it captures words ( \w

= alphanumeric and hyphenated) between single quote or ( |

) numeric unspecified values.

See demo here

For code example:



var str = "heres:a:func('var1', 'var2', 'var3', 2)"
var reg=new RegExp("('\\w+'|\\d+)", "g");
var i= 0;
var arr = [];
str.replace(reg,function(m,group) {arr[i++]=group})

      

console.log (arr) gives:

["'var1'", "'var2'", "'var3'", "2"]

      

+1


source


You can do it with one line, but still 2 regexes: 1) remove everything before open (

and close )

, then split on commas with extra spaces. This way we get all var

s, no matter how many variables there are.

var str = "heres:a:func('var1', 'var2', 'var3', 2)";
alert(str.replace(/.*\(|\s*\)\s*$/g, '').split(/\s*,\s*/));
      

Run codeHide result


Alternatively, you can try a kind of fancy regex, but it's not that safe (only works if you've formatted the data correctly):

var re = /('[^']*?'|\b\d+\b),?(?=(?:(?:[^']*'){2})*[^']*\)$)/g; 
var str = 'heres:a:func23(\'var1\', \'var2\', \'var3\', 2, \'2345\')';
while ((m = re.exec(str)) !== null) {
    document.getElementById("res").innerHTML += m[1] + "<br/>";
}
 
      

<div id="res"/>
      

Run codeHide result


0


source


As I cannot add a comment, I am posting an answer.

var str = "heres:a:func('var1', 'var2', 'var3', 2)"
var args = /\(\s*([^)]+?)\s*\)/.exec(str);
if (args[1]) {
   args = args[1].split(/\s*,\s*/);
   console.log(args);
   alert(args);
} 
      

Run codeHide result


or try it here: https://jsfiddle.net/oz3Ljfe1/3/

0


source







All Articles