Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression match in javascript

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?

like image 348
Jaison Justus Avatar asked Mar 28 '12 05:03

Jaison Justus


People also ask

How do you match a 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).

What does match () return JavaScript?

JavaScript String match() The match() method returns an array with the matches. The match() method returns null if no match is found.

How do you check if a string matches a regex in JS?

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.

How use JavaScript match method?

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.


1 Answers

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.

like image 128
Another Code Avatar answered Oct 11 '22 23:10

Another Code