gpt4 book ai didi

Java 如何查找特定字符串后面的特定行?

转载 作者:行者123 更新时间:2023-12-02 05:24:00 25 4
gpt4 key购买 nike

我从 BufferedReader 获取了一条文本,我需要在特定字符串之后获取特定行

这是示例文本:

<img src="https://example.com/image1.jpg">
<img src="https://example.com/image2.jpg">
<img src="https://example.com/image3.jpg">
<img src="https://example.com/image4.jpg">
<all>
<img src="https://example.com/image9.jpg">
<img src="https://example.com/image11.jpg">
<img src="https://example.com/image15.jpg">

带换行符的示例

<img src="https://example.com/image1.jpg">
<img src="https://example.com/image2.jpg">
<img src="https://example.com/image3.jpg">
<img src="https://example.com/image4.jpg">
<all>

<img src="https://example.com/image9.jpg">
<img src="https://example.com/image11.jpg">
<img src="https://example.com/image15.jpg">

其他角色的示例

<img src="https://example.com/image1.jpg">
<img src="https://example.com/image2.jpg">
<img src="https://example.com/image3.jpg">
<img src="https://example.com/image4.jpg">
<all>
UTUYGBLK
<img src="https://example.com/image9.jpg">
<img src="https://example.com/image11.jpg">
<img src="https://example.com/image15.jpg">

我只想要“all”之后的 img src 行,其中 cont 和 end 循环之后。图像编号是随机的,所以我不可能击中其中任何一个。

目前我的代码如下。

while ((line = rd.readLine()) != null) {

if (line.contains("all")) {
line = rd.readLine();
System.out.println(line);
}
}

但是如果“all”后面有一个换行符,我将得到一个空返回...或有趣的字符 UTUYGBLK

最佳答案

您需要在该元素之后循环,直到结果不为空。下面的代码应该防止您在文件结尾后读取行,并且在读取后显示第一行后停止。

boolean loop = true;
// global loop
while ((line = rd.readLine()) != null && loop) {
// line with "all" in it is found?
if(line.contains("all")) {
// Continue going through the input until end of input
while((line = rd.readLine()) != null && loop) {
// When the line is not empty you have found the line after all!
if(!line.isEmpty()) {
System.out.println(line);
// to stop the loops
loop = false;
}
}
}
}

关于Java 如何查找特定字符串后面的特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com