最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular expression to match a word without a character - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question edited May 14, 2016 at 2:18 user177800 asked May 14, 2016 at 1:44 SaharSahar 5622 gold badges5 silver badges11 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 2

This 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]
发布评论

评论列表(0)

  1. 暂无评论