Regular Expression match in javascript
Try it like this:
var formula = 'SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])';
var reg = /\[\w+:\w+\]/g;
matches = formula.match(reg);
Output:
["[A2:A10]", "[B2:B10]", "[C2:C10]", "[D2:D10]"]
Your regex was in the right direction, but didn't include the colon and captured individual characters. The \w
escape sequence I used is a shortcut for a word character ([a-zA-Z0-9_]
), makes it more readable. The g
flag is necessary to get all matches instead of just the first one.
var str = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var matches = str.match(/\[[A-Z0-9:]+\]/g);
alert(matches);
Note, you use the g
flag on the regex to get all the matches.
You can see it working here: http://jsfiddle.net/jfriend00/aTrLU/
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[.*?\]/g;
matches = formula.match(reg);