2

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.

Sahar
  • 542
  • 1
  • 5
  • 11

4 Answers4

2

This works for your case:

/.*\b[^\se]+\b.*/gi

Regex101

timolawl
  • 5,434
  • 13
  • 29
1

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
Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
  • Thanks for your help, but it did not answer the question. The regex is supposed to match `god father` and `good game`, but this regex does not. – Sahar May 25 '16 at 21:50
  • @Sahar you are correct, and I've updated the regex to work as expected. I've also added a short test program and shown the results of running it on the input array that you provided. Thanks! – Michael Gaskill May 25 '16 at 22:20
1
/\b([^ e])+\b/gi

This selects any words that do not contain an e|E.

Joe P.
  • 11
  • 3
0
/\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]
lochiwei
  • 1,240
  • 9
  • 16