java - IndexOF 没有错,但我 :)
问题描述
我需要帮助:
我正在制作一个可以从 html 中读出特定字符串的程序。
我的代码:
String html = client.request(URL);
// is more or less = [html]<meta itemProp="name" content="[my target]"/> [html]
String searchString = "<meta itemProp=\"name\" content=\"";
String searchEndString = "\"/>";
while (true) {
int from = html.indexOf(searchString);
if (from == -1) {
break;
}
String temp = html.substring(from);
int to = temp.indexOf(searchEndString, from); //this is somehow -1
String name = temp.substring(searchString.length(), to);
// DO sth with name
html = temp.substring(to);
}
例外:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:
第 45 行 java.lang.String.substring(Unknown Source) 处的 -32
String name = temp.substring(searchString.length(), to);
抛出异常,因为在to
那个-1
时候。
为什么会int to = temp.indexOf(searchEndString, from);
导致-1
我已经尝试了一个自定义html
字符串,它有效。
提前致谢 :)
解决方案
推荐阅读
- python - 如何使用 Python 访问 Amazon EMR 错误消息
- python - 无法在 macOS Big Sur 上使用 PyQt5 获取屏幕截图
- presto - 配置 apache 超集以通过 LDAP 连接到 presto 的正确方法是什么?
- python - threading code.InteractiveInterpreter 并在执行命令时获取输出
- ffmpeg - ffmpeg推视频成功了,为什么一开始就出错了?
- java - 使用构造函数注入的组件测试问题
- python - 如何使用网页上的按钮调用类的方法 - Django -python
- amazon-web-services - VPN 站点到站点选项中的“内部隧道 IPv4 CIDR”是什么意思?
- reactjs - 我应该如何解决“预计在箭头函数结束时返回一个值。”?
- codeigniter - 在 codeigniter 3 中调用未定义的方法 CI_DB_mysqli_driver::prepare()?