c# - 精确值匹配索引

标签 c#

环境: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/

相关文章:

c# - 如何为 WPF 网格中的所有元素设置特定的高度/宽度?

c# - 从字母数字到非字母数字排序

c# - 如何调试卡在 Windows Phone 8.1 上的应用程序

c# - 为什么不触发 MouseEnter 事件?

c# - 如何找到xml元素的最小值和最大值

c# - Travis CI 上使用 Mono 的 NuGet 包恢复失败

c# - C# 中的用户控件与自定义控件

c# - 为什么在此实现中插入排序总是击败合并排序?

c# - 查找 Button/UIElement 在屏幕上相对于网格 Windows Phone 的位置

c# - 使用表名访问DataSet中的DataTable