gpt4 book ai didi

java - 如何使用 Java 在文本文件中复制以特定字符开头和结尾的字符串

转载 作者:行者123 更新时间:2023-11-30 03:50:41 25 4
gpt4 key购买 nike

我已使用 Java 将网页的页面源代码复制到文本文件中。

文件中有以下字符串,我只需复制数字并将它们保存在另一个文件中。

'数字', '[670341345,670341248,670320495,670318700,670317434,670315031,670314751,670314299,670311573]');

简单地以“'numbers' , '[ ”开头并以“]')结尾的字符串;”

这是我所做的:

import java.io.*;
import java.net.*;


public class copyID {
public static void main (String[] args) throws Exception {

String url = "http://www.google.com";
StringBuilder fullPage = new StringBuilder();
URL olx = new URL (url);

URLConnection conn = olx.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String inputLine;
while((inputLine = in.readLine()) != null){

fullPage.append(inputLine+"\n");
}
in.close();
saveToFile(fullPage.toString()); }

public static void saveToFile(String input){
try{
BufferedWriter out = new BufferedWriter (new FileWriter("ID_List.txt"));

out.write(input);
out.close();

}
catch (IOException e){}

}



}

我该怎么做?我正在使用 Eclipse。

最佳答案

您的搜索字符串非常具体,因此我认为即使是最顽固的反正则表达式 HTML 人员也可以在这里使用正则表达式。

下面的代码显示了如何隔离相关文本并提取数字。我认为您可以研究如何解决其余问题:

String example = "sdflkjsdflskdfs0980sdflkjmlsdf'numbers', '[1231231"
+ "23,123123123,1231232,345634,3453534,123123]');asdasdasdasd";

Pattern pattern = Pattern.compile("'numbers', '\\[(.*?)\\]'\\);");
Matcher matcher = pattern.matcher(example);

while (matcher.find()) {
String[] numbers = matcher.group(1).split(",");
for (String s : numbers) {
System.out.println(s);
}

输出:

12312312312312312312312323456343453534123123

关于java - 如何使用 Java 在文本文件中复制以特定字符开头和结尾的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24530564/

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