I need to extract a specific string from a text file that has lines with multiple Delimiters that may be similar or different. For example, lets say I have a text file contains the below lines. Let's consider each text between a delimiter as a segment.
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$
I need to write a code that extracts the text after ABC#12#3#
in all the lines in the text file, based on two inputs.
1) The segment to find (e.g., ABC
)
2) Position of the segment from which I need to extract the text. (e.g., 4
)
So, an input of ABC
and 4th segment will give a result - LINE1
and an input of DEF
and 5th segment will give a result - 1234678985
.
This is what I've got so far regarding the 1st input.
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);
}
}
I've got 2 problems with my code. I don't know how I can use substring
to separate text between SAME delimiters and I'm not sure how to write the code such that it is able to identify all the following special characters as delimiters - {#, $, :}
and thereby consider any text between ANY of these delimiters as a segment.
Answer to this question uses regex which I want to avoid.