我需要從具有多個分隔符的文本文件中提取特定的字符串,這些分隔符可能相似或不同。例如,讓我說我有一個文本文件包含下面的行。讓我們將分隔符之間的每個文本看作一個段。在多個分隔符之間提取文本
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
和第四區段的輸入會給出一個結果 - LINE1
和DEF
和第五區段的輸入會給出一個結果 - 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分隔符之間分隔文本,我不知道如何編寫代碼,以便能夠識別以下所有特殊字符作爲分隔符: - {#, $, :}
,從而考慮ANY之間的任何文本這些分隔符作爲細分。
回答this問題使用正則表達式,我想避免。
你有很多特殊字符出現,請注意,'replaceAll'接受*正則表達式*。 – Maroun
[Java:use split()with multiple delimiters]可能重複](http://stackoverflow.com/questions/5993779/java-use-split-with-multiple-delimiters) – hotzst