简体   繁体   English

正则表达式匹配没有字符的单词

[英]Regular expression to match a word without a character

This is the question:这是问题:

We have strings containing 2 words, like:我们有包含 2 个单词的字符串,例如:

["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 .正则表达式应该匹配god fathergood game因为它们每个都有一个不包含字母e (god and good)的单词,并且它不应该匹配bed time和“red地毯”,因为字符串中的两个单词都有字母e

I was thinking about /\\b[^e]*\\b/g , but it matches all of these strings.我在考虑/\\b[^e]*\\b/g ,但它匹配所有这些字符串。

This works for your case:这适用于您的情况:

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

Regex101正则表达式101

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'可能包含“e”的单词和不包含“e”的单词
  • words that do not contain an 'e' and words that may contain an 'e'不包含“e”的词和可能包含“e”的词

Note that [az] may be used in place of \\w if that's what the solution requires.请注意,如果解决方案需要,可以使用[az]代替\\w 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

这将选择任何不包含 e|E 的单词。

/\b[^\We]+\b/g
  • \\W means NOT a "word" character. \\W表示不是“单词”字符。
  • ^\\W means a "word" character. ^\\W表示“单词”字符。
  • [^\\We] means a "word" character, but not an "e". [^\\We]表示“单词”字符,但不是“e”。

see it in action: word without e看到它在行动:没有e的词

"and" Operator for Regular Expressions正则表达式的“and”运算符

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM