返回匹配的正则表达式的部分 [英] Return the part of the regex that matched

查看:62
本文介绍了返回匹配的正则表达式的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 OR (管道)的正则表达式中,是否有方便的方法来获取匹配的表达式部分。

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

示例:

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

返回 Camel 。我想要的是 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.

推荐答案

很简单,没有。

正则表达式匹配与输入字符串有关,而不是用于创建正则表达式的文本。请注意,该文本可能会丢失,理论上甚至不需要。一个等价的匹配器可以用这样的东西构建:

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.

抱歉。

这篇关于返回匹配的正则表达式的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆