C#的String.Split 針對 (Multiple characters)
緣由: 這是專案會用到的拆字,要全文檢索用,例如 [商業,男人],會拆成 [商業 AND 男人],但要再轉換成ID
目標: 商業 AND 男人 ---> 111 AND 123
split的依據變成是 AND (Multiple characters)
一般習慣用的 string.split('char')無法滿足
幸好還有另一個方式
Regex.Split(value, "AND")
直接看程式碼
{
string[] keywords;
if (keyword.IndexOf("AND") > 0)
{
keywords = Regex.Split(keyword, "AND");
keyword = null;
for (int i = 0; i < keywords.Length; i++)
{
if (i == 0)
keyword = "\"" + getKeywordID(keywords[i].Trim()) + "\"";
else
keyword = keyword + " AND " + "\"" + getKeywordID(keywords[i].Trim()) + "\"";
}
}
else if (keyword.IndexOf("OR") > 0)
{
keywords = Regex.Split(keyword, "OR");
keyword = null;
for (int i = 0; i < keywords.Length; i++)
{
if (i == 0)
keyword = "\"" + getKeywordID(keywords[i].Trim()) + "\"";
else
keyword = keyword + " OR " + "\"" + getKeywordID(keywords[i].Trim()) + "\"";
}
}
else
{
keyword = "\"" + getKeywordID(keyword) + "\"";
}
return keyword;
}