Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the part of the regex that matched

In a regular expression that uses OR (pipe), is there a convenient method for getting the part of the expression that matched.

Example:

/horse|caMel|TORTOISe/i.exec("Camel");

returns Camel. What I want is caMel.

I understand that I could loop through the options instead of using one big regular expression; that would make far more sense. But I'm interested to know if it can be done this way.

like image 248
ColBeseder Avatar asked Dec 25 '22 23:12

ColBeseder


1 Answers

Very simply, no.

Regex matches have to do with your input string and not the text used to create the regular expression. Note that that text might well be lost, and theoretically is not even necessary. An equivalent matcher could be built out of something like this:

var test = function(str) {
    var text = str.toLowerCase();
    return text === "horse" || text === "camel" || text === "tortoise";
};

Another way to think of it is that the compilation of regular expressions can divorce the logic of the function from their textual representation. It's one-directional.

Sorry.

like image 151
Scott Sauyet Avatar answered Jan 03 '23 01:01

Scott Sauyet