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

6 answers

Try the following:

var formula = 'SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])';
var reg = /\[\w+:\w+\]/g;
matches = formula.match(reg);



["[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.



var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[.*?\]/g;
matches = formula.match(reg);




var str = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";

var matches = str.match(/\[[A-Z0-9:]+\]/g);


Note that you are using a flag g

in the regex to get all matches.

You can see how it works here:



Required regex



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



Your regex does not include a colon :


Try this: /\[([0-9A-Z:]+)\]/

in particular why I have quotes and unquoted squares.

Also, your input string is not being quoted.



I believe you have forgotten the quotes. Also, you need a global flag as well. Here's 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);




All Articles