Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, does an empty regex pattern have defined behavior?

var pattern = /(?:)/

From my testing, it seems to match everything. Is this the defined behavior?

like image 857
ClosureCowboy Avatar asked May 23 '11 01:05

ClosureCowboy


2 Answers

This doesn't directly answer the question, but here's what the spec has to say about the empty regular expression:

From 15.5.4.14 String.prototype.split (separator, limit)

The value of separator may be an empty String, an empty regular expression, or a regular expression that can match an empty String.

And from 7.8.5 Regular Expression Literals

NOTE Regular expression literals may not be empty; instead of representing an empty regular expression literal, the characters // start a single-line comment. To specify an empty regular expression, use: /(?:)/ .

So given that it is an accepted value for the separator in .split(), I would guess that it is the defined behavior as a way to split on every character.

"fjeij;als#%^&é.\n isoij\t;oi`1=+-]\r".split(/(?:)/);

["f", "j", "e", "i", "j", ";", "a", "l", "s", "#", "%", "^", "&", "é", ".", "
", " ", "i", "s", "o", "i", "j", "  ", ";", "o", "i", "`", "1", "=", "+", "-", "]", "
"]
like image 166
user113716 Avatar answered Nov 12 '22 17:11

user113716


/(?:)/ matches "nothing", which matches everything. There is nothing in everything. Heh heh.
Yes, I would expect this.

like image 27
Cheeso Avatar answered Nov 12 '22 17:11

Cheeso