I have a text file that reads
NFR1: (some text)
NFR2: (some text)
NFR3: (some text)
I wanted to group all strings in a text file that had the pattern"N".
This is code I have so far:
import java.util.List;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
List<String> result = new ArrayList<String>();
Pattern patt = Pattern.compile("^N.*");
BufferedReader r = new BufferedReader(new FileReader("fileName"));
String line;
try {
while ((line = r.readLine()) != null) {
Matcher m = patt.matcher(line);
while (m.find()) {
int start = m.start(0);
int end = m.end(0);
result.add(m.group());
System.out.println(result);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The output is as follows:
[NFR1:]
[NFR1:,NFR2:]
[NFR1:,NFR2:,NFR3]
How do I get the array to read just
[NFR1:,NFR2:,NFR3]
without the other two elements above?
When I add the line of code to get the last element:
if (result != null && !result.isEmpty()) {
System.out.println("Last element is:");
System.out.println(result.get(result.size()-1));
}
The output is:
The last element is:
NFR1:
The last element is:
NFR2:
The last element is:
NFR3:
What am I doing wrong?
System.out.println(result);at the end of try-catch block? You are printing the arraylist in every iteration of the loop.