user429400
user429400

Reputation: 3325

nodejs regex - need help to understand code

Can you please explain what this code does (from Blair Mitchelmore jquery.query-2.1.6.js)?

    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+?)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };

I've just started to learn the nodejs regex, and I want to make sure I understand the above code.

Thanks, Li

Upvotes: 0

Views: 1095

Answers (2)

John Dvorak
John Dvorak

Reputation: 27287

var m, rx = /\[([^[]*)\]/g,

A variable gets declared, a regex gets defined and stored as a second variable.

match = /^([^[]+?)(\[.*\])?$/.exec(path),

Still within the variable declaration block, this regex gets executed on the function argument:

  • /^ regex delimiter, start-of-string
  • ([^[]+?) match at least one character, as few as possible, don't match any opening square brackets. Captured.
  • (\[.*\])? match an opening square bracket, anything at all, then a closing square bracket. Captured along with the brackets.
  • $/ end of string, regex delimiter.

This regex will separate the path in two arguments. Anything before the first square bracket, and anything inside any square brackets (mandatory).

base = match[1], tokens = [];

This will call the first match "base" while assuming the regex did match, and it will create an empty array named "tokens".

while (m = rx.exec(match[2]))
  tokens.push(m[1]);

This will match the first defined regex over the square brackets repeatedly, and build an array from the captured values. The regex matches:

  • \[ an opening square bracket,
  • ([^[]*) anything else that doesn't include an opening square bracket (captured),
  • \] and a closing square bracket

At this point, assuming the path argument was well-formed, the base holds the parts before the square brackets in the path, and tokens holds the contents of the square brackets.

return [base, tokens];

Returns said two variables as a two-element array (I won't judge the coding style here; let's just say I'd prefer an object)

Upvotes: 2

Firas Dib
Firas Dib

Reputation: 2621

Are you curious what the actual code does or what the regular expressions do?

The code is quite basic, but here's an explanation with possible matches for both of your regular expressions:

/\[([^[]*)\]/g -> http://regex101.com/r/uP0hR6

/^([^[]+?)(\[.*\])?$/ -> http://regex101.com/r/wG3aG4

I hope this helps!

Upvotes: 1

Related Questions