Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numbers between square bracket and separated by comma

Tags:

java

regex

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?

like image 757
user1314404 Avatar asked May 30 '13 02:05

user1314404


1 Answers

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.

like image 77
greedybuddha Avatar answered Nov 14 '22 23:11

greedybuddha