是否首选在RegExp对象或String对象上使用方法?

时间:2011-09-08 21:14:30

标签: javascript

Javascript中的RegExp个对象和String对象都有正则表达式匹配方法。

RegExp个对象有方法

  • EXEC
  • 测试

String个对象有方法

  • 匹配
  • 搜索

execmatch方法非常相似:

/word/.exec("words");
//Result: ["word"]
"words".match(/word/);
//Result: ["word"]

/word/.exec("No match");
//Result: null
"No match".match(/word/);
//Result: null

/word/g.exec("word word");
//Result: ["word"]
"word word".match(/word/g);
//Result: ["word", "word"]

testsearch也非常相似:

/word/.test("words");
//Result: true
"words".search(/word/);
//Result: 0
//Which can converted to a boolean:
"word".search(/word/) > -1;
//Result: true

/word/.test("No match");
//Result: false
"No match".search(/word/) > -1;
//Result: false

是否首选使用RegExp个对象或String个对象上的方法?

2 个答案:

答案 0 :(得分:5)

主要是个人偏好

这主要是个人偏好,但功能略有不同(参见上一段的差异)。除非你想开始对性能测量进行基准测试并将问题转化为性能测试,否则它主要是个人偏好。

我更喜欢这样做:

string.match(/word/)

因为我认为这使得代码读起来像我的大脑一样考虑操作。我正在使用字符串对象并在其中查找特定的正则表达式。对我来说,在字符串中查找某些东西是字符串对象上的方法是有道理的。这对我来说就是:

object.action(tool)

在我看来,面向对象的代码应该如何工作。

如果你有:

/word/.match(string)
然后对我来说感觉就像:

tool.action(object)

我发现它不那么合乎逻辑,也不那么面向对象了。是的,/word/在技术上也是一个对象,但它不是我试图操作的对象,我认为它更像是我正在使用的工具或参数。

显然两者都有效。你可以自己决定你喜欢哪个。

一个主要差异

我认为你只能在正则表达式对象上做一些事情。例如,如果要匹配正则表达式的所有匹配项,则必须创建正则表达式对象,将“g”选项传递给它,然后多次调用re.exec()以获取每个匹配项,直到exec返回null指示没有比赛了。我不认为你可以用string.match()来做到这一点。

答案 1 :(得分:2)

使用全局标记match时,execg之间存在一些差异。您无法使用match遍历全局发布,而使用exec则可以:

var string="xabx xnnx";
var regexp=new RegExp('x([^x]*)x','g');

// match returns the list of matching parts:
string.match(regexp) // ["xabx", "xnnx"]

// with exec you could build a loop:
var match=regexp.exec(string);
while (match) {
    console.log(match);
    match=regexp.exec(string);
}
// This loops through matches and returns subpatterns too:
// ["xabx", "ab"]
// ["xnnx", "nn"]

index与全球化match对象一起使用时,RegExp根本不起作用:

var r=/b/g;
r.exec("0123b56b").index // 4
r.exec("0123b56b").index // 7
"0123b56b".match(r).index // undefined
"0123b56b".match(/b/).index // 4