Need to find a regular expression for any word except word1 or word2

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

should do what you need.

(?!...) is a negative lookahead assertion that ensures that it is not possible to match the enclosed expression at the current position.


To match any word that is a sequence of one or more letters, digits or underscores (since you mention you want to match all words using \w+) except word1 and word2 you may use a negative lookahead solution with word boundaries \b:

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

See the regex demo. Note that in PostgreSQL regex, \b must be replaced with \y.

Here are some quick code snippets:

  • scala - """\b(?!(?:word1|word2)\b)\w+""".r.findAllIn(text).toList (see demo)
  • groovy - text.findAll(/\b(?!(?:word1|word2)\b)\w+/) (see demo)
  • kotlin - Regex("""\b(?!(?:word1|word2)\b)\w+""").findAll(text).map{it.value}.toList() (see demo)
  • powershell - select-string -Path $input_path -Pattern '\b(?!(?:word1|word2)\b)\w+' -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
  • c++ - 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()); (see demo)
  • vb.net - Dim matches() As String = Regex.Matches(text, "\b(?!(?:word1|word2)\b)\w+").Cast(Of Match)().Select(Function(m) m.Value).ToArray()
  • swift - 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+"#))
  • javascript - text.match(/\b(?!(?:word1|word2)\b)\w+/g) (see demo)
  • r - regmatches(text, gregexpr("(*UCP)\\b(?!(?:word1|word2)\\b)\\w+", text, perl=TRUE)) (see demo) or stringr::str_extract_all(text, "\\b(?!(?:word1|word2)\\b)\\w+") (see demo)
  • ruby - text.scan(/\b(?!(?:word1|word2)\b)\w+/) (see demo)
  • java - 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()); } (see demo)
  • php - if (preg_match_all('~\b(?!(?:word1|word2)\b)\w+~u', $text, $matches)) { print_r($matches[0]); } (see demo)
  • python - re.findall(r"\b(?!(?:word1|word2)\b)\w+", text) (see demo)
  • c# - Regex.Matches(text, @"\b(?!(?:word1|word2)\b)\w+").Cast<Match>().Select(x=>x.Value) (see demo)
  • grepbash - grep -oP '\b(?!(?:word1|word2)\b)\w+' file (demo)
  • postgresql - REGEXP_MATCHES(col, '\y(?!(?:word1|word2)\y)\w+', 'g') (demo)
  • perl - @list = ($str =~ m/\b(?!(?:word1|word2)\b)(\w+)/g); (demo)

Tags:

Regex