简体   繁体   中英

Extract numbers between square bracket and separated by comma

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM