Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all substrings inside a string that match a regular expression [duplicate]

Possible Duplicate:
How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

In Javascript, is it possible to find the starting and ending indices of all substrings within a string that match a regular expression?

Function signature:

function getMatches(theString, theRegex){
    //return the starting and ending indices of match of theRegex inside theString
    //a 2D array should be returned
}

For example:

getMatches("cats and rats", /(c|r)ats/);

should return the array [[0, 3], [9, 12]], which represents the starting and ending indices of "cats" and "rats" within the string.

like image 280
Anderson Green Avatar asked Aug 20 '12 02:08

Anderson Green


People also ask

How do I find substrings in regex?

String indexOf() Method The most common (and perhaps the fastest) way to check if a string contains a substring is to use the indexOf() method. This method returns the index of the first occurrence of the substring. If the string does not contain the given substring, it returns -1.

How do I find all matches in regex?

The method str. match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.

Which method is used to check match in string in regular expression?

The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

What is regex match in c#?

Matches Method. CsharpProgrammingServer Side Programming. The method matches instances of a pattern and is used to extract value based on a pattern.


2 Answers

Use match to find all substrings that match the regex.

> "cats and rats".match(/(c|r)ats/g)
> ["cats", "rats"]

Now you can use indexOf and length to find the start/end indices.

like image 85
sachleen Avatar answered Oct 04 '22 00:10

sachleen


function getMatches(theString, theRegex){
    return theString.match(theRegex).map(function(el) {
        var index = theString.indexOf(el);
        return [index, index + el.length - 1];
    });
}
getMatches("cats and rats", /(c|r)ats/g); // need to use `g`
like image 44
xdazz Avatar answered Oct 04 '22 00:10

xdazz