I have a text file:
90,-5 ,, 37 , 1 99
0 -55,,,
,,,11
I need to extract the integers into an array. I have been traing to do so with this code:
File file=new File("2.txt");
Scanner in=new Scanner(file);
in.useDelimiter(" *|,*|\\n");
int[] b=new int[20];
int i=0;
while(in.hasNextInt()){
b[i]=in.nextInt();
i++;
}
in.close();
What i doing wrong?
There is a mismatch between the delimiter expression and the separator characters. In this case, it is simpler to match the characters in which you are interested rather then separator characters. A precompiled Pattern
can be used for greater performance.
Pattern pattern = Pattern.compile("-?\\d+");
BufferedReader reader = new BufferedReader(new FileReader("2.txt"));
String line;
while ((line = reader.readLine()) != null) {
Matcher m = pattern.matcher(line);
while (m.find()) {
System.out.println(m.group(0));
}
}
I think you may need to read the documentation on patterns, because in a quick brush through now it doesn't look like |
is the union operator. Also, wouldn't \\\\n
be a literal backslash n, not the newline character?
http://docs.oracle.com/javase/tutorial/essential/regex/index.html
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.