Reputation: 2793
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?
Upvotes: 9
Views: 26342
Reputation: 6817
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
Upvotes: 2
Reputation: 3151
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.
Upvotes: 19
Reputation: 707158
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/
Upvotes: 2
Reputation: 25322
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);
Upvotes: 0
Reputation: 25135
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[.*?\]/g;
matches = formula.match(reg);
Upvotes: 3
Reputation: 77454
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.
Upvotes: 1