Skip to content Skip to sidebar Skip to footer

Regular Expression To Match A Word Without A Character

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

Solution 1:

This works for your case:

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

Regex101

Solution 2:

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

Solution 3:

Solution 4:

/\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) andnot(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 andB= [^Ab]

Post a Comment for "Regular Expression To Match A Word Without A Character"