环境:microsoft visual studio 2008 c#
如何获取在字符串中找到的整个单词的索引
string dateStringsToValidate = "birthdatecake||birthdate||other||strings";
string testValue = "birthdate";
var result = dateStringsToValidate.IndexOf(testValue);
也不一定非得像我这样,比如用正则表达式好还是其他方法好?
更新: 这个词是生日而不是生日蛋糕。它不必检索匹配项,但索引应该找到正确的词。我不认为 IndexOf 是我要找的东西。抱歉不清楚。
最佳答案
为此使用正则表达式
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);
关于c# - 精确值匹配索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9829550/