I have input strings that look something like these
inspect [foo - bar] with [errors - 15]
create [doodle]
force delete [quux]
That is, lines which contain information within square brackets.
What I want is to take one of those lines at a time and get an array like
["inspect", "[foo - bar], "with", "[errors - 15]"]
Using a regular expression it’s easy to collect the bracketed expressions and the parts between the bracketed expressions separately:
var src = "inspect [foo - bar] with [errors - 15]"
var regexBracketed = /\[[a-zA-Z0-9_\- ]+\]/g;
// this returns an array of the bracketed expressions
console.log(src.match(regexBracketed));
// and this returns an array of the parts between the expressions
console.log(src.split(regexBracketed));
Is there a simple way to get everything in just one array? Maybe I’m attacking this entirely the wrong way.
are you referring to groups (capturing parentheses)?
/(.*)/?https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions#Using_Parenthesized_Substring_Matches
for example, if you want to capture the strings in the brackets, then you can use this:
you can add
\s*to the expression to trim whitespace too.