Reputation: 537
I have a text file as follow:
Past Dues / Refunds / Subsidy
Arrears / Refunds
Amount
2013.23
Period to which
it relates
Since OCT-15
Now, how do I extract the data in the next line of "Amount". I have tried it using boolean, checking the above and below line.
Is there any other way to do it.
My code:
boolean isGroup=false;
while(line = br.readline() != null){
if(line.equals("Amount"){
isGroup=true;
}
if(line.equals("Period to which") && isGroup)
isGroup=false;
if(isGroup){
//read line and check whether it is null or not
String amount = line;
}
}
Please Help. Thanks
Upvotes: 1
Views: 263
Reputation: 1065
this is how you would do @sln answer in java
String text = "Past Dues / Refunds / Subsidy\n" +
"Arrears / Refunds\n" +
"Amount\n" +
"2013.23\n" +
"Period to which\n" +
"it relates\n" +
"Since OCT-15";
Pattern pattern = Pattern.compile("(?mi)^Amount\\s(?<amount>\\d+\\.\\d{2})");
Matcher matcher = pattern.matcher(text);
if(matcher.find()){
String amount = matcher.group("amount");
System.out.println("amount: "+ amount);
}
Upvotes: 1
Reputation: 13490
Your approach is perfectly fine. You made a little mistake by setting the boolean, then using on the same iteration of the loop.
If you do the following you should be fine:
String amount = "No amount found";
boolean isGroup=false;
while(line = br.readline() != null) {
// Check all your conditions to see if this is the line you care about
if(isGroup){
amount = line;
isGroup = false; // so you only capture this once
continue;
}
else if (isOtherCondition) {
// handle other condition;
isOtherCondition = false; // so you only capture this once
continue;
}
// Check the contents of lines to see if it's one you want to read next iteration
if(line.equals("Amount"){
isGroup=true;
}
else if (line.equals("Some Other Condition")) {
isOtherCondition = true;
}
}
This is all you need. The break;
is just so you don't have to worry about what happens after you grab the amount.
Upvotes: 2
Reputation:
If the file is average size, you could use a regex.
Just read in the entire file into a string.
To use a regex it would be something like this.
Result is in capture group 1.
"(?mi)^\\s*Amount\\s+^\\s*(\\d+(?:\\.\\d*)?|\\.\\d+)\\s*$"
(?mi) # Multi-line mode, case insensitive
^ # Beginning of line
\s* Amount \s+
^ # Beginning of line
\s*
( # (1 start), Numeric value
\d+
(?: \. \d* )?
| \. \d+
) # (1 end)
\s*
$ # End of line
Upvotes: 1