Is there a JavaScript regular expression equivalent to the intersection operator (&&) in Java regular expressions?

In Java regular expressions, you can use the intersection operator && in character classes to briefly describe them, for example.

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

Is there an equivalent in JavaScript?

+7
source share
3 answers

Is there an equivalent in JavaScript?

The simple answer is no, no. This is Java specific syntax.

See: Book of Regular Expressions by John Goyvaerts and Stephen Levitan. Here, look at the appropriate section .

It may not be necessary to speak, but the following JavaScript code:

 if(s.match(/^[az]$/) && s.match(/[^bc]/)) { ... } 

will do the same as Java code:

 if(s.matches("[az&&[^bc]]")) { ... } 
+11
source

You can get the same result as Java regular expressions in JavaScript by writing longhand character classes like

 Java JavaScript English ------------ ---------- ------- [az&&[def]] [def] d, e, or f [az&&[^bc]] [ad-z] a through z, except for b and c 

In some cases, this is a bit more verbose / obscure, e.g.

 Java JavaScript ---------------- ----------- [AZ&&[^QVX]] [A-PR-UWYZ] [AZ&&[^CIKMOV]] [ABD-HJLNP-UW-Z] 
+1
source

As others have said, there is no equivalent, but you can achieve the && effect using a forecast. Conversion:

 [classA&&classB] 

becomes:

 (?=classA)classB 

For example, this is in Java:

 [az&&[^bc]] 

has the same behavior as this:

 (?=[az])[^bc] 

which is fully supported in JavaScript. I do not know the relative performance of the two forms (in machines like Java and Ruby that support both).

Since the && operator is commutative, you can always use both sides for the (positive or negative) part in front.

The intersection of a class with a negative class can also be implemented with a negative forecast. Thus, the above example could also be converted to:

 (?![bc])[az] 
+1
source

All Articles