我正在做一个应用程序,它应该获取整个 website-html 文本并将其放入字符串中。 然后我想使用 System.out.println 来显示该字符串的一个特定片段。我的代码
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("www.example-blahblahblah.com");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine.substring(inputLine.indexOf("<section class=\"horoscope-content\"><p>")+1, inputLine.lastIndexOf("</p")));
in.close();
}
}
它应该显示下面输入的文本:
<section class="horoscope-content">
<p>Text text text text</p>
相反,我有这个:
线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1 在 java.lang.String.substring(来源未知) 在 URLConnectionReader.main(URLConnectionReader.java:14)
我该怎么办?
最佳答案
您应该使用更具包容性的正则表达式而不是 indexOf
,以便在对输入进行细微修改时更加稳定:
Pattern pattern = Pattern.compile("<section\\s+class\\s*=\\s*\"horoscope-content\"\\s*>\\s*<p>(.*?)</p>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println(matcher.group());
System.out.println("Text in paragraph: " + matcher.group(1));
}
这将容忍换行符和其他空白字符。
关于java - 需要特定的弦乐部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20132930/