Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two regular expressions

Tags:

syntax

regex

ruby

I want to return true if a string starts with a consonant. I have two conditions and don't know how to combine them.

1) it is a letter 2) it is not a vowel

!!(s[0] =~ /([a-z]&&[^aeiou])/i)

I tried all sorts of other syntax like:

!!(s[0] =~ /([a-z])([^aeiou])/i)
!!(s[0] =~ /(([a-z])([^aeiou]))/i)

is there any way to do this in one regex? Do I need to check each condition separately?

like image 956
Paul Nogas Avatar asked Dec 15 '22 05:12

Paul Nogas


1 Answers

You can combine the character classes using the && operator:

/[a-z&&[^aeiou]]/

Note that the && operator is used inside the character class, not afterwards.

From the documentation:

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]/
like image 163
Stefan Avatar answered Dec 17 '22 19:12

Stefan