mercredi, novembre 12, 2008

Java Extracting only first Integer value from String

Here is the new java function that extracts the 1st Integer value from String:
String s = new String("Eric Mariacher 1965 AoxomoxoA 1967 Cowabunga 2009 ");
Matcher matcher = Pattern.compile("\\d+").matcher(s);
matcher.find();
int i = Integer.valueOf(matcher.group());

Here is the old java function that extracts the 1st Integer value from String:
   3:    public static int findNextValidInteger(String s) throws Exception {
4:
5: // detect 1st digit after start of string
6: int beginIndex=0;
7: int endIndex=1;
8: int length=s.length();
9: while(!s.substring(beginIndex,endIndex).matches("\\d")) {
10: beginIndex++;
11: endIndex++;
12: if(endIndex>length) {
13: throw new Exception("No digit found.");
14: }
15: }
16: int i_startNumber= beginIndex;
17:
18: // detect 1st non digit after start previously detected 1st digit
19: beginIndex=i_startNumber;
20: endIndex=i_startNumber+1;
21: while(s.substring(beginIndex,endIndex).matches("\\d")) {
22: beginIndex++;
23: endIndex++;
24: if(endIndex>length) {
25: break;
26: }
27: }
28: int i_endNumber= beginIndex;
29:
30: // return absolute value of integer
31: return Integer.valueOf(s.substring(i_startNumber, i_endNumber));
32: }
33:
Can also be done the following way, but may take lot of resources if String
is very long and you only need the 1st Integer.
35:
36: StringTokenizer str = new StringTokenizer("A 1965 Eric");
37:
38: while(str.hasMoreElements()) {
39: System.out.println(str.nextElement());
40: int i = Integer.parseInt(str.nextElement());
41: }
42:

Aucun commentaire: