正则表达式执行只返回第一场比赛 [英] Regex exec only returning first match

查看:148
本文介绍了正则表达式执行只返回第一场比赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 golfscript语法页上实现以下正则表达式搜索。

I am trying to implement the following regex search found on golfscript syntax page.

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

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

Input is only ever the first match of the regexp. for example: "hello" "world" should return ["hello", "world"] but it only returns ["hello"].

推荐答案

RegExp。 exec 只能一次返回一个匹配结果。

RegExp.exec is only able to return a single match result at once.

要检索多个匹配项,您需要运行 exec <表达式对象上的/ code>多次。例如,使用简单的while循环:

In order to retrieve multiple matches you need to run exec on the expression object multiple times. For example, using a simple while loop:

var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;

var match;
while ((match = ptrn.exec(input)) != null) {
    console.log(match);
}

这会将所有匹配记录到控制台。

This will log all matches to the console.

请注意,为了使其工作,您需要确保正则表达式具有 g (全局)标志。此标志确保在对表达式执行某些方法后, lastIndex 属性已更新,因此在上一个结果后,将进一步调用

Note that in order to make this work, you need to make sure that the regular expression has the g (global) flag. This flag makes sure that after certain methods are executed on the expression, the lastIndex property is updated, so further calls will start after the previous result.

这篇关于正则表达式执行只返回第一场比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆