【发布时间】:2016-01-03 09:41:51
【问题描述】:
我需要从一个文本文件中提取一个特定的字符串,该文件包含多个可能相似或不同的分隔符的行。例如,假设我有一个包含以下行的文本文件。让我们将分隔符之间的每个文本视为一个段。
ABC#12#3#LINE1####1234678985$
DEF#XY#Z:1234:1234561230$
ABC#12#3#LINE TWO####1234678985$
DEF#XY#Z:1234:4564561230$
ABC#12#3#3RD LINE####1234678985$
DEF#XY#Z*1234:7894561230$
我需要编写一个代码,根据两个输入提取文本文件中所有行中ABC#12#3# 之后的文本。
1) 要查找的段(例如,ABC)
2) 我需要从中提取文本的段的位置。 (例如,4)
因此,ABC 和第 4 段的输入将给出结果 - LINE1,DEF 和第 5 段的输入将给出结果 - 1234678985。
到目前为止,这是我对第一个输入的了解。
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.contains(find)){ // find is the 1st input - (e.g., ABC)
System.out.println("Line to be replaced - "+ line);
int ind1 = line.indexOf(findlastchar+"*")+1;
int ind2 = line.indexOf("*");
System.out.println("Ind1 is "+ ind1+ " and Ind2 is " + ind2);
System.out.println("findlastchar is "+findlastchar+"#");
remove = line.substring(line.indexOf(findlastchar)+1, line.indexOf("#"));
System.out.println("String to be replaced " + remove);
content = content.replaceAll(remove, replace);
}
}
我的代码有 2 个问题。我不知道如何使用 substring 分隔 SAME 分隔符之间的文本,并且我不确定如何编写代码以便能够将以下所有特殊字符识别为分隔符 - {#, $, :} 并因此考虑任何这些分隔符之间的任何文本作为一个段。
this 问题的答案使用我想避免的正则表达式。
【问题讨论】:
-
那里有很多特殊字符,注意
replaceAll接受regex。
标签: java regex delimiter text-extraction csv