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.
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.
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.
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