String.IndexOf()方法不符合我的预期。
我希望它不会找到匹配项,因为您所输入的确切单词不在str。
string str = "I am your Friend";
int index = str.IndexOf("you",0,StringComparison.OrdinalIgnoreCase);
Console.WriteLine(index);
Run Code Online (Sandbox Code Playgroud)
输出5
我的预期结果是-1,因为字符串不包含您。
您面临的问题是因为IndexOf匹配单个字符或较大字符串中的字符序列(搜索字符串)。因此,“我是您的朋友”包含序列“您”。仅匹配单词,您必须在单词级别上考虑事物。
例如,您可以使用正则表达式来匹配单词边界:
private static int IndexOfWord(string val, int startAt, string search)
{
// escape the match expression in case it contains any characters meaningful
// to regular expressions, and then create an expression with the \b boundary
// characters
var escapedMatch = string.Format(@"\b{0}\b", Regex.Escape(search));
// create a case-sensitive regular expression object using the pattern
var exp = new Regex(escapedMatch, RegexOptions.IgnoreCase);
// perform the match from the start position
var match = exp.Match(val, startAt);
// if it's successful, return the match index
if (match.Success)
{
return match.Index;
}
// if it's unsuccessful, return -1
return -1;
}
// overload without startAt, for when you just want to start from the beginning
private static int IndexOfWord(string val, string search)
{
return IndexOfWord(val, 0, search);
}
Run Code Online (Sandbox Code Playgroud)
在您的例子中,您将尝试匹配\byou\b,由于边界的要求而无法匹配your。
在此处查看有关正则表达式中单词边界的更多信息。
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |