Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Regular expression in JavaScript, always ‘undefined’ if use a grouping followed by a question mark

Regular expression in JavaScript, always ‘undefined’ if use a grouping followed by a question mark

Problem

What I'm trying to do is to extract matching patterns, but one of the patterns could be optional. Let's go example directly.

The target text I'm trying to match would be,

\n\n#####\n#####

And my Regular Expression is,

/(#{5})?/

(The reason why I use ? here is because the particular pattern could be optional. For example I don't want the match to be totally a miss rather than just an 'undefined' for this very pattern.)

What I expected as returned by str.match() is,

[ '#####',
  '#####',
  index: 12,
  input: '\n\n#####\n#####' ]

But actually it's,

[ '',
  undefined,
  index: 0,
  input: '\n\n#####\n#####' ]

If I use following pattern instead, it'll work fine.

/(#{5})+/

Why?

I tried this in both nodejs/chrome and IE but neither one work which means this behavior is consistent across JS engine. But it doesn't behave the same way one of many tools i tried, regexpal. I'm not sure if that's the tool's own issue or just different implementation.

Problem courtesy of: Chundong Wang

Solution

var re = /(#{5})/;
console.log ("\n\n#####\n#####".match (re));
console.log ("\n\nfoo>\n".match (re));

output:

[ '#####',
  '#####',
  index: 12,
  input: '\n\n#####\n#####' ]
null

If it's optional the regexp fails when there's no match and if it fails it returns null.

> /a/.exec("a")
[ 'a', index: 0, input: 'a' ]
> /a/.exec("b")
null
> "a".match(/a/)
[ 'a', index: 0, input: 'a' ]
> "b".match(/a/)
null

Also, don't use String#match(), it's slower than RegExp#exec() and both return the same:

match() vs exec()

Solution courtesy of: Gabriel Llamas

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Regular expression in JavaScript, always ‘undefined’ if use a grouping followed by a question mark

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×