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

cll*_*pse 5 javascript regex

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

这是正则表达式:

([a-z]+)((\d+)([a-z]+))?,?
Run Code Online (Sandbox Code Playgroud)

使用时"water2cups,flour4cups,salt2teaspoon"你应该得到:

[
    ["water", "2cups", "2", "cups"]
    ["flout", "4cups", "4", "cups"]
    ["salt", "2teaspoon", "2", "teaspoon"]
]
Run Code Online (Sandbox Code Playgroud)

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

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

更新

我正在使用正则表达式:

"water2cups,flour4cups,salt2teaspoon".match(/([a-z]+)((\d+)([a-z]+))?,?/g);
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 12

创建RegExp

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

var rex = /([a-z]+)((\d+)([a-z]+))?,?/;
Run Code Online (Sandbox Code Playgroud)

或一个字符串

var rex = new RegExp("([a-z]+)((\\d+)([a-z]+))?,?");
Run Code Online (Sandbox Code Playgroud)

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

全球旗帜

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

var rex = /([a-z]+)((\d+)([a-z]+))?,?/g;
Run Code Online (Sandbox Code Playgroud)

要么

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

使用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,flour4cups,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] + "|");
    }
}
Run Code Online (Sandbox Code Playgroud)

(该log函数只是将文本附加到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|
Run Code Online (Sandbox Code Playgroud)

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