This is the question:
We have strings containing 2 words, like:
["bed time", "red carpet", "god father", "good game"]
The regex should match god father
and good game
because each of them have a word that does not contain the letter e
(god and good), and it should not match bed time
and "red carpet" as both words inside the strings have the letter e
.
I was thinking about /\b[^e]*\b/g
, but it matches all of these strings.
This is the question:
We have strings containing 2 words, like:
["bed time", "red carpet", "god father", "good game"]
The regex should match god father
and good game
because each of them have a word that does not contain the letter e
(god and good), and it should not match bed time
and "red carpet" as both words inside the strings have the letter e
.
I was thinking about /\b[^e]*\b/g
, but it matches all of these strings.
4 Answers
Reset to default 2This works for your case:
/.*\b[^\se]+\b.*/gi
Regex101
Use this:
/^(\w+ [^e]+|[^e ]+ \w+)$/i
It searches for either one of:
- words that may contain an 'e' and words that do not contain an 'e'
- words that do not contain an 'e' and words that may contain an 'e'
Note that [a-z]
may be used in place of \w
if that's what the solution requires. Assuming that the examples are truly representative of the inputs, either should work adequately.
This code tests the regex against the input array:
phrases = ["bed time", "red carpet", "god father", "good game"]
phrases.each do |phrase|
puts "#{phrase}" if phrase.match(/^(\w+ [^e]+|[^e ]+ \w+)$/i)
end
The results are:
god father
good game
/\b([^ e])+\b/gi
This selects any words that do not contain an e|E.
/\b[^\We]+\b/g
\W
means NOT a "word" character.^\W
means a "word" character.[^\We]
means a "word" character, but not an "e".
see it in action: word without e
"and" Operator for Regular Expressions
BTW, I think this pattern can be used as an "and" operator for regular expressions.
In general, if:
A = not a
B = not b
then:
[^AB] = not(A or B)
= not(A) and not(B)
= a and b
Difference Set
So, if we want to implement the concept of difference set in regular expressions, we could do this:
a - b = a and not(b)
= a and B
= [^Ab]