2 回答
TA贡献1803条经验 获得超6个赞
所以你有这样的例子
#CH id="" tvg-name="Example1" tvg-logo="http...
并试图在这些字符串上拆分
" tvg-name=\" "
" \"tvg-logo= "
这些字符串都不在示例中。附加了一个虚假的空格,第二个开头的空格在错误的位置。
修复字符串,这里有一个简洁但完整的程序来演示
interface Split {
static void main(String[] args) {
String line = "#CH id=\"\" tvg-name=\"Example1\" tvg-logo=\"http...";
String[] first_scan = line.split(" tvg-name=\"", 2);
String first = first_scan[1]; // <--- out of bounds
String[] second_scan = first.split("\" tvg-logo=", 2);
String second = second_scan[0];
System.err.println(second);
}
}
当然,如果您有任何以 开头'#'但不匹配的行,您也会遇到类似的问题。
使用正则表达式和捕获组可能会更好地完成这类事情。
TA贡献1876条经验 获得超6个赞
最后一个双引号后面有一个空格,tvg-name=\"其中与您的示例中的数据不匹配。
当您使用 split withline.split(" tvg-name=\"", 2)时,返回数组中的第一项将是#CH id="",第二部分将是Example1" tvg-logo="http..."
如果您想获得 的值,tvg-name=您可以使用带有捕获组的正则表达式,您将使用否定字符类捕获而不是双引号[^"]+
tvg-name="([^"]+)"
try {
FileInputStream VOD = new FileInputStream("channels.txt");
BufferedReader buffer_r = new BufferedReader(new InputStreamReader(VOD));
String line;
ArrayList<String> name_channels = new ArrayList<String>();
while((line = buffer_r.readLine()) != null ){
if(line.startsWith("#")){
String regex = "tvg-name=\"([^\"]+)\"";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
name_channels.add(matcher.group(1));
}
} else {
// ...
}
}
for(int i = 0; i < name_channels.size(); i++){
System.out.println("Channel: " + name_channels.get(i));
}
}catch(Exception e){
System.out.println(e);
}
添加回答
举报