【发布时间】:2021-11-22 02:06:59
【问题描述】:
基本上我需要一个正则表达式,如果字符串是一个单词 (\w+),它将返回 true,除非它是单词 word1 或 word2。
我已经尝试了很多事情,但我认为我什至没有接近。救命!
【问题讨论】:
标签: regex
基本上我需要一个正则表达式,如果字符串是一个单词 (\w+),它将返回 true,除非它是单词 word1 或 word2。
我已经尝试了很多事情,但我认为我什至没有接近。救命!
【问题讨论】:
标签: regex
匹配由一个或多个字母、数字或下划线组成的任何单词(因为您提到要使用\w+匹配所有单词)除了word1和word2你可以使用negative lookahead 和word boundaries \b 的解决方案:
\b(?!(?:word1|word2)\b)\w+
请参阅regex demo。请注意,在 PostgreSQL 正则表达式中,\b 必须替换为 \y。
这里有一些快速的代码 sn-ps:
"""\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+' file (demo)REGEXP_MATCHES(col, '\y(?!(?:word1|word2)\y)\w+', 'g') (demo)@list = ($str =~ m/\b(?!(?:word1|word2)\b)(\w+)/g); (demo)【讨论】:
就是这样:
^(?!word1|word2)\w*
【讨论】:
【讨论】:
为什么要为此使用正则表达式?
伪代码:
return (str != word1 AND str != word2)
【讨论】: