Reputation: 1
I need to take input from the file of the format
2 (3,4) (5,6) 3 (6,5) (7,8)
where I want just the integer value to store in some variable ,I dont want brackets and commas so how do I get this using pattern-match?
Upvotes: 0
Views: 71
Reputation: 11
I prefer the String method split, which allows use of regular expressions. Here's some example code to run for each line of input from your file, assuming you have instantiated an instance variable named contents of type ArrayList<Integer>:
public void readLine(String line) {
String delimiters = "[ ,()]+"; // regular expression
String[] tokens = line.split(delimiters);
for (String token : tokens) {
try {
Integer i = Integer.parseInt(token); // convert String to Integer
contents.add(i);
} catch (NumberFormatException e) {
// TODO: handle exception
}
}
}
The split method creates a few extra (empty) tokens, which the try/catch eliminates. Hope this helps.
Upvotes: 1
Reputation: 121971
You can read the integers directly from the file using java.util.Scanner
and specify a delimiter using Scanner.useDelimiter(Pattern)
, where the delimiter would be a regular expression ("[,() ]{1,}"
for example). The Scanner
methods hasNextInt()
and nextInt()
can be used to read the integers.
Upvotes: 0
Reputation: 2475
You can use String#replaceAll("[^0-9]", "")
to remove any non-numeric characters and Integer.valueOf(String)
to get an Integer.
Upvotes: 0