IndexOf 的行为与预期的 C# 不同

IndexOf behaves different than expected C#

我得到了以下三行代码,其中 html 是一个 html 页面,存储为一个字符串。

int startIndex = html.IndexOf("<title>") + 8; // <title> plus a space equals 8 characters
int endIndex = html.IndexOf("</title>") - 18; // -18 is because of the input, there are 18 extra characters after the username.
result = new Tuple<string, bool>(html.Substring(startIndex, endIndex), false);

输入 <title>Username012345678912141618</title> 我希望得到 Username 的输出。但是,代码找不到 </title>。我不确定出了什么问题。有谁知道什么会导致这种行为? 我已经用三个不同的网页(都来自同一站点)对其进行了测试,我检查了其中的内容。

String.Substring 有 2 个参数有下一个签名 - String.Substring(int startIndex, int length) 第二个参数是 the number of characters in the substring。所以你需要做这样的事情(考虑到你的评论):

int startIndex = html.IndexOf("<title>") + 8;
int endIndex = html.IndexOf("</title>")
var result = new Tuple<string, bool>(html.Substring(startIndex, endIndex - startIndex - 18), false);

我意识到 OP 正在询问 IndexOf 方法,但这里有一个使用不同方法的解决方案 -- 正则表达式,它非常适合“手术式”从字符串中提取数据。

以下模式是从 html 标签中提取“用户名”所需的全部内容:

var pattern = $@"<title>Username(.+)</title>";

该模式将按如下方式使用:

var pattern = $@"<title>Username(.+)</title>";
var ms = Regex.Match(html, pattern, RegexOptions.IgnoreCase);
var userName = ms.Groups.Count > 0 ? ms.Groups[1].Value : string.Empty;

Regex 的一个优点是您可以使用您正在使用的确切文本来搜索您需要的数据。无需在索引中添加或减去“位置”。

您需要添加:

using System.Text.RegularExpressions;

您打算实施的 class Regex