7
votes

nombre hors de la chaîne en Java

J'ai quelque chose comme "ali123hgj". Je veux avoir 123 en Integer. Comment puis-je le faire en Java?


3 commentaires

Qu'en est-il de "abc123def567ghi" ou "abcdef" ?


Vous avez toujours 3 caractères avant le numéro ou ce n'est qu'un exemple?


Ce n'est pas seulement trois caractères. C'est un nombre compris entre 0 ou plusieurs personnages. Il peut être "123", "SDFS", "123FDHF", "FGDKJHGF123"


6 Réponses :


8
votes

Utilisez le REGEXP suivant (voir http://java.sun.com.com / Docs / Livres / Tutoriel / Essential / Regex / ): XXX Pré>

Par: P>

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
}


0 commentaires

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

0 commentaires

0
votes

Vous pouvez probablement le faire dans ces lignes:

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)));
}


0 commentaires

0
votes
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 commentaires

0
votes
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;
Input "asg123d ddhd-2222-33sds --- ---222 ss---33dd 234" results in this ouput
[123, -2222, -33, -222, -33, 234]

0 commentaires

1
votes

Ceci est le Google Guava # Charmatcher Way. xxx

Si vous ne vous souciez que de correspondre aux chiffres ASCII, utilisez xxx

Si vous ne vous souciez que de correspondre aux lettres de l'alphabet latin, utilisez xxx


0 commentaires