Java data structure read numeric content from a string [duplicate]
Possible Duplicate:
Using Regular Expressions to Extract a Value in Java
For example, the input string is AB100FF10
. I need to read 100
and 10
from the string. Is there any classes/objects in Java that I can use?
try this
String[] nums = "AB100FF10".split("\\D+");
for (String num : nums) {
System.out.println(num);
}
Other than that, you could try passing the string to a class like Scanner
Scanner scan = new Scanner("AB100FF10").useDelimiter("\\D+");
while (scan.hasNextInt()) {
System.out.println(scan.nextInt());
}
Edit: using \\D
instead of \\w
as a delimiter, as Bohemian suggested in his answer and comments.
Just use split(<non-digits>)
, like this:
String[] numbers = "AB100FF10CCC".replaceAll("(^\\D*|\\D*$)", "").split("\\D+"); // "[100, 10]"
Now numbers
contains an array of Strings that are all guaranteed to be numeric. You can use Integer.parseInt()
to get ints
.
The replaceAll("(^\\D*|\\D*$)", "")
is used to trim non-digits from the front and back of the input string, otherwise split() will give you a blank string as the first/last element. It just makes to code simpler, rather than having to test the first/last specially.
As a method, it would look like this:
public static int[] parseInts(String input) {
String[] numbers = input.replaceAll("(^\\D*|\\D*$)", "").split("\\D+");
int[] result = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
result[i] = Integer.parseInt(numbers[i]);
}
return result;
}
If you want to get only integers you can do the following:
ArrayList<Integer> numbers = new ArrayList<Integer>();
char[] characters = "AB100FF10".toCharArray();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < characters.length; i++) {
if (Character.isDigit(characters[i]))
buf.append(characters[i]);
else if (buf.length() != 0) {
numbers.add(Integer.parseInt(buf.toString()));
buf = new StringBuffer();
}
}
After that you will have an arrayList of numbers
I think pattern might be a better solution to because pattern object is more powerful comparing to simple String split() method.
for example, following code can resolve the same problem without any exception
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(test[0]);
while(m.find()){
int x = Integer.parseInt( m.group() );
}
But if I use String.split()
, there is one NumberFormatException is hard to dealt with.For example, below code can't escape NumberFormatException
for(int i = 0 ; i < test.length; i++){
String[] numstr= test[i].split("\\D+");
try{
for(int j=0; j<numstr.length;j++){
if( numstr[j] == null || numstr[j] == ""){
System.out.println("empty string \n");
}
else
Integer.parseInt(numstr[j]);
}catch(NumberFormatException ie){
ie.printStackTrace();
}
}
精彩评论