ZEE*_*ZEE 0 javascript regex capture
在这个正则表达式多次捕获我必须添加"g"标志来获取所有项目...
"aaa bbb ccc \n.000.\n \n.111.\n sd555 dsf \n.222.\n ddd".match(/^.(.*).$/gm)
当我添加"g"(全局)标志?如何访问捕获的组...应该有3像["000","111","222"],但我不知道如何访问它们. ..我一直得到[".000.",".111.",".222."] <<注意单词前后的点
如果您想在全局正则表达式中获取捕获组,则match不幸的是,您无法使用它.相反,你需要exec在正则表达式上使用:
var myregex = /^.(.*).$/gm;
var result, allMatches = [];
while((result = myregex.exec(mystring)) != null) {
var match = result[1]; // get the first match pattern of this match
allMatches.push(match);
}
Run Code Online (Sandbox Code Playgroud)
使用全局正则表达式,match返回所有整个匹配的数组,并且永远不会返回捕获组. exec返回单个匹配及其所有捕获组.要获得所有匹配,您必须exec多次调用,直到它最终返回null.
请注意,exec依赖于正则表达式维护状态,因此必须将正则表达式保存在变量中:
while((result = /^.(.*).$/gm.exec(mystring)) != null) // BAD and WRONG!
Run Code Online (Sandbox Code Playgroud)
这是错误的,因为每个循环都有一个新的正则表达式,它不知道它应该返回这个循环的匹配.(或者,更确切地说,它不知道lastIndex以前的正则表达式.)
| 归档时间: |
|
| 查看次数: |
1540 次 |
| 最近记录: |