I have the string SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10]) and I need to get the elements [A2:A10],[B2:B10],[C2:C10],[D2:D10] in an array, so I used match() in js. The code snippet is
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[(a-zA-Z0-9)+\]/;
matches = formula.match(reg);
But I am not getting the match. I hope the regular expression is wrong. I am very poor in building regular expression. What will be the correct regular expression?
6 Answers 6
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.
Comments
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[.*?\]/g;
matches = formula.match(reg);
4 Comments
.* basically means 'match anything', and the ? right after it makes the quantifier lazy so it doesn't match the rest of the input string too, but only up to the next ]."[]", when you need to constrain the dot.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/
Comments
The regex you need is
/\[[A-Z][0-9]+:[A-Z][0-9]+\]/gi
The g modifier indicates that we should do a global mtching and return all the results, not just the first
The i modifier indicates that we need a case-insensitive matching
An assumption made is that you don't want to include [E2:E10:], because of extra semicolon
Comments
Your regexp doesn't include the colon :.
Try this: /\[([0-9A-Z:]+)\]/ , in particular why I have quoted and unquoted square brackets there.
Plus, your input string isn't quoted.
Comments
I believe you forgot the quotes. Also, what you need is also the global flag. Here the code:
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[[0-z]+:[0-z]+\]/g;
var matches = formula.match(reg);