Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript regex equivalent to the intersection (&&) operator in Java regexes?

In Java regexes, you can use the intersection operator && in character classes to define them succinctly, e.g.

[a-z&&[def]]    // d, e, or f
[a-z&&[^bc]]    // a through z, except for b and c

Is there an equivalent in JavaScript?

like image 664
Paul D. Waite Avatar asked Jul 06 '11 11:07

Paul D. Waite


2 Answers

Is there an equivalent in JavaScript?

Simple answer: no, there's not. It is specific Java syntax.

See: Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan. Here's a sneak-peek to the relevant section.

Probably needless to say, but the following JavaScript code:

if(s.match(/^[a-z]$/) && s.match(/[^bc]/)) { ... }

would do the same as the Java code:

if(s.matches("[a-z&&[^bc]]")) { ... }
like image 196
Bart Kiers Avatar answered Sep 27 '22 20:09

Bart Kiers


As others have said, there isn't an equivalent, but you can achieve the effect of && using a look-ahead. The transformation is:

[classA&&classB]

becomes:

(?=classA)classB

For instance, this in Java:

[a-z&&[^bc]]

has the same behavior as this:

(?=[a-z])[^bc]

which is fully supported in JavaScript. I don't know the relative performance of the two forms (in engines like Java and Ruby that support both).

Since the && operator is commutative, you can always use either side for the (positive or negative) look-ahead part.

Intersection of a class with a negated class can also be implemented with negative look-ahead. So the example above could also have been transformed to:

(?![bc])[a-z]
like image 36
Ted Hopp Avatar answered Sep 27 '22 21:09

Ted Hopp