环境:microsoft visual studio 2008 c#
如何获取字符串中找到的整个单词的索引
string dateStringsToValidate = "birthdatecake||birthdate||other||strings";
string testValue = "birthdate";
var result = dateStringsToValidate.IndexOf(testValue);
Run Code Online (Sandbox Code Playgroud)
它不一定是我这样做的方式,例如,使用正则表达式或其他方法会更好吗?
更新: 这个词是生日,而不是birthdatecake.它不必检索匹配,但索引应该找到正确的单词.我不认为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;
}
Run Code Online (Sandbox Code Playgroud)
在此处了解有关c#中正则表达式选项的更多信息
根据您的需要,另一个选择是分割字符串(因为我看到你有一些分隔符).请注意,此选项返回的索引是按字数计算的索引,而不是字符数(在本例中为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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1696 次 |
| 最近记录: |