使用此
string dateStringsToValidate = "birthdatecake||birthdate||other||strings";
string testValue = "strings";
var result = WholeWordIndexOf(dateStringsToValidate, testValue);
// ...
public int WholeWordIndexOf(string source, string word, bool ignoreCase = false)
{
string testValue = "\\W?(" + word + ")\\W?";
var regex = new Regex(testValue, ignoreCase ?
RegexOptions.IgnoreCase :
RegexOptions.None);
var match = regex.Match(source);
return match.Captures.Count == 0 ? -1 : match.Groups[0].Index;
}
正則表達式瞭解更多關於在C#中的正則表達式選項here
另一種選擇,根據您的需要,是分割字符串(因爲我看到你有一定的分隔符) 。請注意,此選項返回的索引是按字數統計的索引,而不是字符數(在此情況下爲1,因爲C#具有基於零的陣列)。
string dateStringsToValidate = "birthdatecake||birthdate||other||strings";
var split = dateStringsToValidate.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
string testValue = "birthdate";
var result = split.ToList().IndexOf(testValue);
咦? – SLaks 2012-03-22 19:59:52
他意味着像'全字'匹配。 – payo 2012-03-22 20:02:25
您的確切測試用例最簡單的解決方案是將您的testValue更改爲「birthdate |」,但我認爲您需要一個更靈活的解決方案。你需要更確切地定義你的問題。 – 2012-03-22 20:16:21