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?
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]]")) { ... }
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With