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?
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
JavaScript String match() The match() method returns an array with the matches. The match() method returns null if no match is found.
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With