首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >正则表达式exec仅返回第一个匹配

正则表达式exec仅返回第一个匹配
EN

Stack Overflow用户
提问于 2011-03-12 22:26:07
回答 2查看 55.2K关注 0票数 55

我正在尝试实现在golfscript syntax page上找到的以下正则表达式搜索。

代码语言:javascript
复制
var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;
input = ptrn.exec(input);

输入只是regexp的第一个匹配。例如:"hello" "world"应该返回["hello", "world"],但它只返回["hello"]

EN

回答 2

Stack Overflow用户

发布于 2015-02-02 02:25:40

可以对字符串调用match方法,以检索匹配的整个集合:

代码语言:javascript
复制
var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;
var results = "hello world".match(ptrn);

results是(根据正则表达式):

代码语言:javascript
复制
["hello", " ", "world"]

match spec is here

票数 24
EN

Stack Overflow用户

发布于 2016-11-03 17:55:17

我不明白你问题中的"hello" "world"是什么意思,它是用户输入还是正则表达式,但是有人告诉我RegExp对象有一个状态--它开始搜索的lastIndex位置。它不会一次返回所有结果。它只带来第一个匹配,您需要恢复.exec才能从lastIndex position开始获得其余结果:

代码语言:javascript
复制
const re1 = /^\s*(\w+)/mg; // find all first words in every line
const text1 = "capture discard\n me but_not_me" // two lines of text
for (let match; (match = re1.exec(text1)) !== null;) 
      console.log(match, "next search at", re1.lastIndex);

打印

代码语言:javascript
复制
["capture", "capture"] "next search at" 7
[" me", "me"] "next search at" 19

为您的结果构建迭代器的函数式JS6方法如下

代码语言:javascript
复制
RegExp.prototype.execAllGen = function*(input) {
    for (let match; (match = this.exec(input)) !== null;) 
      yield match;
} ; RegExp.prototype.execAll = function(input) {
  return [...this.execAllGen(input)]}

还请注意,与poke不同,我更巧妙地使用了封装在for-loop中的match变量。

现在,您可以在一行代码中轻松捕获匹配项

代码语言:javascript
复制
const matches = re1.execAll(text1)

log("captured strings:", matches.map(m=>m[1]))
log(matches.map(m=> [m[1],m.index]))
for (const match of matches) log(match[1], "found at",match.index)

哪种打印

代码语言:javascript
复制
"captured strings:" ["capture", "me"]

[["capture", 0], ["me", 16]]
"capture" "found at" 0
"me" "found at" 16
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5283071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档