微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

迷失在翻译中 – C#正则表达式使用JavaScript正则表达式

我在将我的工作C#正则表达式转换为JavaScript的正则表达式实现时遇到了一些麻烦.

这是正则表达式:

([a-z]+)((\d+)([a-z]+))?,?

当用于“water2cups,flour4cups,salt2teaspoon”时,你应该得到:

[
    ["water","2cups","2","cups"]
    ["flout","4cups","4","cups"]
    ["salt","2teaspoon","teaspoon"]
]

……确实如此.在C#中.但不是在JavaScript中.

我知道各实现之间存在一些细微差别.为了让这个表达式在JavaScript中工作,我错过了什么?

更新

我正在使用正则表达式:

"water2cups,salt2teaspoon".match(/([a-z]+)((\d+)([a-z]+))?,?/g);
最佳答案
创建RegExp

您还没有展示如何创建Javascript正则表达式,例如,您使用的是文字

var rex = /([a-z]+)((\d+)([a-z]+))?,?/;

一个字符串

var rex = new RegExp("([a-z]+)((\\d+)([a-z]+))?,?");

如果是后者,请注意我已经逃过了反斜杠.

全球旗帜

认情况下,Javascript正则表达式不是全局的,这可能是您的问题.如果您还没有g标志,请添加

var rex = /([a-z]+)((\d+)([a-z]+))?,?/g;

要么

var rex = new RegExp("([a-z]+)((\\d+)([a-z]+))?,?","g");

使用RegExp #exec而不是String#match

您的编辑说您正在使用String#match来获取一系列匹配项.我不得不承认我几乎没有使用String#match(我使用RegExp #exec,如下所示.)当我使用String#match与你的正则表达式时,我得到……非常奇怪的结果因浏览器而异.使用RegExp #exec循环不会这样做,所以这就是我要做的.

工作实例

代码可以满足您的需求:

var rex,str,match,index;

rex = /([a-z]+)((\d+)([a-z]+))?,?/g;
str = "water2cups,salt2teaspoon";

rex.lastIndex = 0; // Workaround for bug/issue in some implementations (they cache literal regexes and don't reset the index for you)
while (match = rex.exec(str)) {
    log("Matched:");
    for (index = 0; index < match.length; ++index) {
        log("&nbsp;&nbsp;match[" + index + "]: |" + match[index] + "|");
    }
}

(日志函数只是将文本附加到div.)

我的输出是:

Matched:
  match[0]: |water2cups,|
  match[1]: |water|
  match[2]: |2cups|
  match[3]: |2|
  match[4]: |cups|
Matched:
  match[0]: |flour4cups,|
  match[1]: |flour|
  match[2]: |4cups|
  match[3]: |4|
  match[4]: |cups|
Matched:
  match[0]: |salt2teaspoon|
  match[1]: |salt|
  match[2]: |2teaspoon|
  match[3]: |2|
  match[4]: |teaspoon|

(回想一下,在Javascript中,匹配[0]将是整个匹配;然后匹配[1],依此类推你的捕获组.)

原文地址:https://www.jb51.cc/js/429479.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐