简体   繁体   中英

Javascript Regex for capturing variables in curved brackets

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

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

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

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

Results should look like this:

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

This should do ('\\w+'|\\d+) it captures words ( \\w = alphanumeric and hyphen) between single quote or ( | ) numeric unquoted values.

See the demo here

For a code exemple:

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"]

Here's one way to do it:

Regex101 Link

This does not include the quotes by the way, you can add those optionally if you want.

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']

This basically searches for a word character group, and then does a negative and positive lookahead.
Basically

(?!.*\() 

says that I want this to NOT be before any number of characters plus a ( character and

(?=.*\)) 

says that i WANT this to be before any number of characters and a ) character.

Then the capturing group is at the beginning, so you could replace (\\w+) with ([\\'\\w]+) if you wanted to keep the quotes (which I don't think you would right)


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

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

But that will not capture trailing white space, just spaces surrounded by 2 word types (a-Z0-1). Also that only will allow 1 space in the word, so if you need multiples, you'd have to check for that as well. You could modify it to check for any number of word characters or spaces between 2 valid word characters.

For Multiple Spaces:

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

Includes 1 Space: Regex101 Link

Includes Multiple Spaces: Regex101 Link

Edit2:
And just as a final one, if you REALLY want to add a bunch of spaces throughout, you can do this one:

Includes Multiple Spaces, Multiple Times: Regex101 Link

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

You can do it with one line, but still 2 regexps: 1) remove all up to the opening ( and the closing ) , then split on the commas with optional whitespace. This way we'll get all the var s, regardless of how many there are variables.

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

Also, you might try a kind of a fancy regex, but it is not that safe (only works if you have correctly formatted data):

 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"/> 

As i can't add a comment i post a 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); } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM