正则表达式包含多个单词

时间:2017-12-15 19:21:55

标签: c# regex

我正在尝试搜索与整个搜索字词匹配的标题。 我的例子如下所示

string exampleTitle = "apple orange banana";
string term1 = "app bana";
string term2 = "bana app";
string pattern1 = @term1.Replace(" ", "*.*") + "*"; //output:app*.*bana*
string pattern2 = @term2.Replace(" ", "*.*") + "*"; //output:bana*.*app*

//now test
bool isMatch1 = Regex.IsMatch(exampleTitle , pattern1) // true
//now test
bool isMatch2 = Regex.IsMatch(exampleTitle , pattern2) // false

因此pattern2不匹配,因为香蕉来自苹果。但是,当匹配搜索词中的所有单词而没有任何顺序时,我需要为真。

3 个答案:

答案 0 :(得分:4)

正则表达式在这里很棘手。请改用此方法:

const Contact = {
  underNickname: String,
  nickname: String
}

const UserSchema = new Schema()

UserSchema.add({
    nicknames: [Nickname],
    contacts: [Contact],
})

改为使用String exampleTitle = "apple orange banana"; String terms = "app bana"; Boolean found = true; // let's clean things up for malformed input with RemoveEmptyEntries foreach (String term in terms.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)) found &= exampleTitle.Contains(term);

LINQ

答案 1 :(得分:0)

您可以改为使用正则表达式(?=.*app)(?=.*bana)

string pattern1 = "(?=.*"+term1.Replace(" ", ")(?=.*") + ")"; //output:(?=.*app)(?=.*bana)
string pattern2 = "(?=.*" + term2.Replace(" ", ")(?=.*") + ")"; //output:(?=.*app)(?=.*bana)

您可以使用以下方法限制回溯和转发搜索:

string pattern1 = "(?=(?>.*?"+term1.Replace(" ", "))(?=(?>.*?") + "))"; //output:(?=(?>.*?app))(?=(?>.*?bana))
string pattern2 = "(?=(?>.*?" + term2.Replace(" ", "))(?=(?>.*?") + "))"; //output:(?=(?>.*?app))(?=(?>.*?bana))

答案 2 :(得分:-1)

  

当匹配搜索词中没有任何顺序的所有单词时,我需要为真

这可以更清楚地表达为:

String value = reader.readComboBoxValue();
if (value.equalsIgnoreCase("SHOW.DIALOG.ITEM")) {
    comboBox.setSelectedItem(value);
}

正如另一个答案中所提到的,有非正则表达式进行子串匹配可能更合适。