Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the && operator in a character class

Something like this works in Ruby but not in Javascript:

str = "now is the time"
p str.gsub(/[a-z&&[^aeiou]]/, '*')

Notice the && on the second line.

[a-z&&[^aeiou]] works but if you remove the [] around the whole regex and have a-z&&[^aeiou] it won't work. Why? Is this unique to Ruby only? I haven't been able to find much info about this feature.

like image 242
daremkd Avatar asked Nov 29 '25 19:11

daremkd


2 Answers

In regular expressions && is the operator for character class intersection. Ruby's regex engine is called Oniguruma, here's an excerpt from the docs (emphasis added):

Character class

^... negative class (lowest precedence operator)
x-y range from x to y
[...] set (character class in character class)
..&&.. intersection (low precedence at the next of ^)

As to why it doesn't work in JS I don't know, probably because the engine in question doesn't implement this operator. In Java for example it works.

like image 199
Michael Kohl Avatar answered Dec 02 '25 08:12

Michael Kohl


A character class may contain another character class. By itself this isn’t useful because [a-z[0-9]] describes the same set as [a-z0-9]. However, character classes also support the && operator which performs set intersection on its arguments. The two can be combined as follows:

/[a-w&&[^c-g]z]/ # ([a-w] AND ([^c-g] OR z))

This is equivalent to:

/[abh-w]/

http://www.ruby-doc.org/core-2.1.0/Regexp.html#class-Regexp-label-Character+Classes

This operator is indeed not available in Javascript.

like image 31
deceze Avatar answered Dec 02 '25 07:12

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!