I have the following string: "B:0123EH:0234ET:0444" and I need to parse the integers "0123; 0234; 0444" into separate integers.
2 Answers
Regex might be useful:
String numbersStr[] = "B:0123EH:0234ET:0444".split("[A-Z]+:0");
int numbers[] = new int[numbersStr.length - 1];
for (int i = 1; i < numbersStr.length; i++) {
numbers[i - 1] = Integer.parseInt(numbersStr[i]);
System.out.println(numbers[i - 1]);
}
Now you have an array of integers. And for @cricket_007 's comment. You can replace the pattern with [^0-9]+.
PS; This will only work if the pattern you mentioned above is recurring
2 Comments
OneCricketeer
Why not split on
[^0-9]?Peter Chaula
@cricket_007. Nice one. Good idea
You could use something like this:
String str = "B:0123EH:0234ET:0444";
String[] words = str.split("[^0-9]+");
for(String word : words )
System.out.println(word);
It takes the original string and splits it into an array of words, using the regex delimiter for non-numeric values. Then use a for loop to print them out one by one.
2 Comments
OneCricketeer
Why the apostrophe in the regex?
zgc7009
@cricket_007 cause I suck at typing :P