我正在尝试实现在golfscript syntax page上找到的以下正则表达式搜索。
var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;
input = ptrn.exec(input);
输入只是regexp的第一个匹配。例如:"hello" "world"
应该返回["hello", "world"]
,但它只返回["hello"]
。
发布于 2015-02-02 02:25:40
可以对字符串调用match
方法,以检索匹配的整个集合:
var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;
var results = "hello world".match(ptrn);
results
是(根据正则表达式):
["hello", " ", "world"]
发布于 2016-11-03 17:55:17
我不明白你问题中的"hello" "world"
是什么意思,它是用户输入还是正则表达式,但是有人告诉我RegExp对象有一个状态--它开始搜索的lastIndex
位置。它不会一次返回所有结果。它只带来第一个匹配,您需要恢复.exec
才能从lastIndex position开始获得其余结果:
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);
打印
["capture", "capture"] "next search at" 7
[" me", "me"] "next search at" 19
为您的结果构建迭代器的函数式JS6方法如下
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
变量。
现在,您可以在一行代码中轻松捕获匹配项
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)
哪种打印
"captured strings:" ["capture", "me"]
[["capture", 0], ["me", 16]]
"capture" "found at" 0
"me" "found at" 16
https://stackoverflow.com/questions/5283071
复制相似问题