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