Regular expression in javascript
I have a string SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])
and I need to get the items [A2:A10],[B2:B10],[C2:C10],[D2:D10]
in an array, so I used match()
in js. Snippet of code
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[(a-zA-Z0-9)+\]/;
matches = formula.match(reg);
But I don't get the match. I hope the regex is wrong. I am very poor at creating regex. What's the correct regular expression?
source to share
Try the following:
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 did not include colon and single characters. The escape sequence \w
I used is a shortcut for the word character ( [a-zA-Z0-9_]
), which makes it more readable. The flag is g
required to get all matches, not just the first one.
source to share
var str = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var matches = str.match(/\[[A-Z0-9:]+\]/g);
alert(matches);
Note that you are using a flag g
in the regex to get all matches.
You can see how it works here: http://jsfiddle.net/jfriend00/aTrLU/
source to share
Required regex
/\[[A-Z][0-9]+:[A-Z][0-9]+\]/gi
The g modifier indicates that we should do global mtching and return all results, not just the first
The i modifier indicates that we need a case insensitive collation
Made an assumption that you don't want to include [E2: E10:] because of the extra semicolon
source to share