I have an input file:
U10:%x[-2,1]
U11:%x[-1,1]
U12:%x[0,1]q
U13:%x[1,1]
U14:%x[2,1]
U15:%x[-2,1]/%x[-1,1]
U16:%x[-1,1]/%x[0,1]
U17:%x[0,1]/%x[1,1]
U18:%x[1,1]/%x[2,1]
U20:%x[-2,1]/%x[-1,1]/%x[0,1]
U21:%x[-1,1]/%x[0,1]/%x[1,1]
U22:%x[0,1]/%x[1,1]/%x[2,1]
Now I want to read line by line and extract the number to assign to variable i,j
such that:
i=-2, j=1;
i=-1, j=1;
i=0, j=1;
i=1, j=1;
i=2, j=1;
i=-2, j=1; then i=-1, j=1;
i=-1, j=1; then i=0, j=1;
etc.
I am thinking about regular expressions, but strangely this one give no match:
FileReader frr = new FileReader("/Users/home/Documents/input.txt");
BufferedReader brr = new BufferedReader(frr);
String linee;
while ((linee = brr.readLine()) != null) {
String pattern = "\\[(.*?)\\]";
Pattern regex = Pattern.compile(pattern);
Matcher regexMatcher = regex.matcher(linee);
System.out.println(regexMatcher.group());
}
brr.close();
And if I use split, it also return very strange results:
String[] listItems = linee.replaceFirst("^\\[", "").split("(\\(\\d+\\))?\\]?(\\s*,\\s*\\[?|$)");
System.out.println(listItems);
result:
[Ljava.lang.String;@c3bb2b8
etc.
How should I do the above task?
You should switch up your regular expression to capture the two integers inside the brackets. After that you can use regexMatcher.find()
and iterate through all the matches to get the ints.
Example
String pattern = "\\[(-?\\d+),(-?\\d+)\\]";
Pattern regex = Pattern.compile(pattern);
Matcher regexMatcher = regex.matcher(line);
while (regexMatcher.find()){
int i = Integer.valueOf(regexMatcher.group(1));
int j = Integer.valueOf(regexMatcher.group(2));
...
}
This will get you i
and j
for each matching group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With