需要为除word1或word2之外的任何单词找到正则表达式

时间:2011-02-17 14:12:45

标签: regex

基本上我需要一个正则表达式,如果字符串是一个单词(\ w +),它将返回true,如果它是单词word1或word2,则返回。

我尝试过很多东西,但不要以为我就差不多了。救命啊!

4 个答案:

答案 0 :(得分:20)

^(?!(?:word1|word2)$)\w+$

应该做你需要的。

(?!...)negative lookahead assertion,可确保无法匹配当前位置的封闭表达式。

答案 1 :(得分:2)

它是:

^(?!word1|word2)\w*

答案 2 :(得分:2)

要匹配由一个或多个字母,数字或下划线组成的任何单词(因为您提到要使用\w+来匹配所有单词)除外 word1word2,您可以将negative lookahead解决方案与word boundaries \b结合使用:

\b(?!(?:word1|word2)\b)\w+

请参见regex demo。请注意,在PostgreSQL正则表达式中,\b必须替换为\y

以下是一些快速的代码片段:

  • -"""\b(?!(?:word1|word2)\b)\w+""".r.findAllIn(text).toList(请参阅demo
  • -text.findAll(/\b(?!(?:word1|word2)\b)\w+/)(请参阅demo
  • -Regex("""\b(?!(?:word1|word2)\b)\w+""").findAll(text).map{it.value}.toList()(请参阅demo
  • -select-string -Path $input_path -Pattern '\b(?!(?:word1|word2)\b)\w+' -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
  • -std::regex rx(R"(\b(?!(?:word1|word2)\b)\w+)"); std::string s = "Extract all words but word1 and word2."; std::vector<std::string> results(std::sregex_token_iterator(s.begin(), s.end(), rx), std::sregex_token_iterator());(请参阅demo
  • -Dim matches() As String = Regex.Matches(text, "\b(?!(?:word1|word2)\b)\w+").Cast(Of Match)().Select(Function(m) m.Value).ToArray()
  • -extension String { func matches(regex: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex, options: []) let nsString = self as NSString let results = regex.matches(in: self, options: [], range: NSRange(location: 0, length: nsString.length)) return results.map { nsString.substring(with: $0.range) } } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } } print("Extract all words but word1 and word2.".matches(regex: #"\b(?!(?:word1|word2)\b)\w+"#))
  • -text.match(/\b(?!(?:word1|word2)\b)\w+/g)(请参阅demo
  • -regmatches(text, gregexpr("(*UCP)\\b(?!(?:word1|word2)\\b)\\w+", text, perl=TRUE))(请参阅demo)或stringr::str_extract_all(text, "\\b(?!(?:word1|word2)\\b)\\w+")(请参阅demo
  • -text.scan(/\b(?!(?:word1|word2)\b)\w+/)(请参阅demo
  • -Pattern p = Pattern.compile("(?U)\\b(?!(?:word1|word2)\\b)\\w+"); Matcher m = p.matcher(text); List<String> res = new ArrayList<>(); while(m.find()) { res.add(m.group()); }(请参阅demo
  • -if (preg_match_all('~\b(?!(?:word1|word2)\b)\w+~u', $text, $matches)) { print_r($matches[0]); }(请参阅demo
  • -re.findall(r"\b(?!(?:word1|word2)\b)\w+", text)(请参阅demo
  • -Regex.Matches(text, @"\b(?!(?:word1|word2)\b)\w+").Cast<Match>().Select(x=>x.Value)(请参阅demo
  • -grep -oP '\b(?!(?:word1|word2)\b)\w+' filedemo
  • -REGEXP_MATCHES(col, '\y(?!(?:word1|word2)\y)\w+', 'g')demo
  • -@list = ($str =~ m/\b(?!(?:word1|word2)\b)(\w+)/g);demo

答案 3 :(得分:-7)

为什么要为此使用正则表达式?

的伪代码:

return (str != word1 AND str != word2)
相关问题