The empty regular expression

[2012-09-07] dev, javascript, jslang, regexp
(Ad, please don’t block)
This blog post takes a look at the empty regular expression.

The empty regular expression

An empty regular expression matches everything.
    > var empty = new RegExp("");

    > empty.test("abc")
    true
    > empty.test("")
    true
As you probably know, you should only use the RegExp constructor when you are dynamically creating a regular expression. But how do you create it via a literal, given that you can’t use // (the token that starts a line comment)? This is how:
    var empty = /(?:)/;
(?:) is an empty non-capturing group. Such a group leaves few traces and thus is a good choice. Even JavaScript itself uses the above representation when displaying an empty regular expression:
    > new RegExp("")
    /(?:)/

RegExp.prototype

Interestingly, the prototype object of regular expressions is also a regular expression, the empty regular expression:
    > RegExp.prototype
    /(?:)/
You can use RegExp.prototype like any other regular expression:
    > "abc".match(RegExp.prototype)
    [ '', index: 0, input: 'abc' ]

The regular expression that matches nothing

The empty regular expression has an inverse – the regular expression that matches nothing:
    > var never = /.^/;

    > never.test("abc")
    false
    > never.test("")
    false

Related blog post