J'ai quelque chose comme "ali123hgj". Je veux avoir 123 en Integer. Comment puis-je le faire en Java? P>
6 Réponses :
Utilisez le REGEXP suivant (voir http://java.sun.com.com / Docs / Livres / Tutoriel / Essential / Regex / ): 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
}
int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1")); // i == -42
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))); }
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... }
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]
Ceci est le Google Guava # Charmatcher Way. P>
xxx pré> Si vous ne vous souciez que de correspondre aux chiffres ASCII, utilisez P> blockQuote>
xxx pré> Si vous ne vous souciez que de correspondre aux lettres de l'alphabet latin, utilisez p> blockQuote>
xxx pré> blockQuote>
Qu'en est-il de
"abc123def567ghi" code> ou
"abcdef" code>?
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"