1

kw我想在大长度文本中搜索存储在变量中的关键字,并找到找到关键字的第一个 位置。下面的代码不做EXACT keyword match 。

if (webData.IndexOf(kw, StringComparison.OrdinalIgnoreCase) != -1)
{
     found = true;
     int pos = webData.IndexOf(kw, StringComparison.OrdinalIgnoreCase); 
}

如何使用正则表达式来做到这一点?

Match match = Regex.Match(webData, @"^kw$", RegexOptions.IgnoreCase);

if (match.Success)
{
  int pos = //Matching position
}
4

2 回答 2

4

你可以做

Match match = Regex.Match(webData, @"\b"+Regex.Escape(kw)+@"\b", RegexOptions.IgnoreCase);

if (match.Success)
{
  int pos = match.Index;
}

对于完全匹配,您需要使用由表示的边界\b

更多信息在这里

于 2013-01-09T14:00:52.530 回答
1

Match有一个Index属性做你想做的事:

Match match = Regex.Match(webData, pattern, RegexOptions.IgnoreCase);

if (match.Success)
{
  int pos = match.Index;
}

索引 - 在原始字符串中找到捕获的子字符串的第一个字符的位置。(继承自 Capture。)

于 2013-01-09T14:00:06.850 回答