开发者

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 succ开发者_如何转开发inctly, 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]


You can get the same result as the Java regexes in JavaScript by writing out the character classes longhand, e.g.

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

It’s just a bit more verbose/obscure in some circumstances, e.g.

Java               JavaScript
----------------   -----------
[A-Z&&[^QVX]]      [A-PR-UWYZ]
[A-Z&&[^CIKMOV]]   [ABD-HJLNP-UW-Z]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜