Javascript 在RegExp对象或字符串对象上使用方法更可取吗?
Javascript中的Javascript 在RegExp对象或字符串对象上使用方法更可取吗?,javascript,Javascript,Javascript中的RegExp对象和String对象都有正则表达式匹配方法 RegExp对象具有 执行官 试验 String对象具有 匹配 搜寻 exec和match方法非常相似: /word/.exec("words"); //Result: ["word"] "words".match(/word/); //Result: ["word"] /word/.exec("No match"); //Result: null "No match".match(/word/); //
RegExp
对象和String
对象都有正则表达式匹配方法
RegExp
对象具有
- 执行官
- 试验
String
对象具有
- 匹配
- 搜寻
exec
和match
方法非常相似:
/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"]
/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
而测试
和搜索
也非常相似:
/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"]
/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
对象上使用方法是否有偏好?主要是个人偏好
这主要是个人偏好,尽管在能力上存在细微差异(见最后一段)。除非你想开始基准化绩效衡量,并将问题转化为绩效问题,否则这主要是个人偏好
我更喜欢做:
string.match(/word/)
因为我认为这使得代码读起来就像我的大脑思考操作一样。我将获取string对象并在其中查找特定的正则表达式。对我来说,在字符串中查找某些内容是字符串对象上的一个方法,这是有道理的。这对我来说就像:
object.action(tool)
在我看来,这就是面向对象代码的工作方式
如果您有:
/word/.match(string)
对我来说,感觉就像:
tool.action(object)
我发现它的逻辑性和面向对象性要差得多。是的,/word/
在技术上也是一个对象,但它不是我试图操作的对象,我认为它更像是一个工具或一个我正在使用的对象参数
显然这两种方法都有效。你可以自己决定你喜欢哪一种
一个主要区别
我相信只有在正则表达式对象上才能执行一些操作。例如,如果要匹配正则表达式的所有匹配项,则必须创建正则表达式对象,将“g”选项传递给它,然后多次调用
re.exec()
,以获得每个匹配项,直到exec返回null表示不再匹配为止。我认为你不能用string.match()
在使用全局标志g
时,match
和exec
之间有一些区别。您不能使用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"]
当对全球化的RegExp
对象使用match
时,index
根本不起作用:
var r=/b/g;
r.exec("0123b56b").index // 4
r.exec("0123b56b").index // 7
"0123b56b".match(r).index // undefined
"0123b56b".match(/b/).index // 4
除了个人喜好?一般来说,我觉得字符串方法更容易阅读。