Lost in translation - C # regex in javascript regex

I'm having trouble translating my working C # regular expression into a JavaScript regular expression implementation.

Here's the regex:

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

When used in "water2cups,flour4cups,salt2teaspoon"you should get:

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

... And so it is. In C #. But not in JavaScript.

I know that there are some slight differences between implementations. What am I missing to make this expression work in JavaScript?

Update

I use regex like this:

"water2cups,flour4cups,salt2teaspoon".match(/([a-z]+)((\d+)([a-z]+))?,?/g);
+5
source share
2 answers

Create RegExp

You have not shown how you create a Javascript regular expression, for example, do you use a letter:

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

or string

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,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] + "|");
    }
}

( 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|

(, Javascript match[0] , match[1] .. .)

+13

# "@", (). , Javascript , "" , ,

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

All Articles