2010-04-04 11 views
7

Ho qualcosa come "ali123hgj". voglio avere 123 in numero intero. come posso farlo in java?numero di stringa in java

+4

Che dire di '" abc123def567ghi "' o '" abcdef "'? – kennytm

+1

Hai sempre 3 caratteri prima del numero o è solo un esempio? – lbedogni

+0

non è solo tre caratteri. È un numero compreso tra 0 o più caratteri. può essere "123", "sdfs", "123fdhf", "fgdkjhgf123" –

risposta

8

Utilizza il seguente RegExp (vedi http://java.sun.com/docs/books/tutorial/essential/regex/):

\d+ 

By:

final Pattern pattern = Pattern.compile("\\d+"); // the regex 
final Matcher matcher = pattern.matcher("ali123hgj"); // your string 

final ArrayList<Integer> ints = new ArrayList<Integer>(); // results 

while (matcher.find()) { // for each match 
    ints.add(Integer.parseInt(matcher.group())); // convert to int 
} 
11
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", "")); 
// i == 1234 

Nota come questo "fondere" le cifre provenienti da diverse parti delle stringhe in un unico numero . Se hai solo un numero in ogni caso, allora funziona ancora. Se si desidera solo il primo numero, allora si può fare qualcosa di simile:

int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1")); 
// i == -42 

La regex è un po 'più complicato, ma sostituisce in pratica l'intera stringa con la prima sequenza di cifre che esso contiene (con optional segno meno), prima di utilizzare Integer.parseInt per analizzare il numero intero.

0

Probabilmente si potrebbe farlo in queste righe:

Pattern pattern = Pattern.compile("[^0-9]*([0-9]*)[^0-9]*"); 
Matcher matcher = pattern.matcher("ali123hgj"); 
boolean matchFound = matcher.find(); 
if (matchFound) { 
    System.out.println(Integer.parseInt(matcher.group(0))); 
} 

E 'facilmente adattabile a molteplici gruppo numero pure. Il codice è solo per orientamento: non è stato testato.

0
int index = -1; 
for (int i = 0; i < str.length(); i++) { 
    if (Character.isDigit(str.charAt(i)) { 
     index = i; // found a digit 
     break; 
    } 
} 
if (index >= 0) { 
    int value = String.parseInt(str.substring(index)); // parseInt ignores anything after the number 
} else { 
    // doesn't contain int... 
} 
0
public static final List<Integer> scanIntegers2(final String source) { 
    final ArrayList<Integer> result = new ArrayList<Integer>(); 
    // in real life define this as a static member of the class. 
    // defining integers -123, 12 etc as matches. 
    final Pattern integerPattern = Pattern.compile("(\\-?\\d+)"); 
    final Matcher matched = integerPattern.matcher(source); 
    while (matched.find()) { 
    result.add(Integer.valueOf(matched.group())); 
    } 
    return result; 

ingresso "asg123d ddhd-2222-33sds --- --- --- 222 ss 33dd 234" I risultati di questo ouput [123, -2222, -33, -222, - 33, 234]

1

Questo è il modo Google Guava #CharMatcher.

String alphanumeric = "12ABC34def"; 

String digits = CharMatcher.JAVA_DIGIT.retainFrom(alphanumeric); // 1234 

String letters = CharMatcher.JAVA_LETTER.retainFrom(alphanumeric); // ABCdef 

Se vi interessa soltanto per abbinare le cifre ASCII, utilizzare

String digits = CharMatcher.inRange('0', '9').retainFrom(alphanumeric); // 1234 

Se vi interessa soltanto per abbinare le lettere dell'alfabeto latino, utilizzare

String letters = CharMatcher.inRange('a', 'z') 
         .or(inRange('A', 'Z')).retainFrom(alphanumeric); // ABCdef 
Problemi correlati