在String中提取整数部分

提取字符串的整数部分的最佳方法是什么

Hello123 

你如何获得123部分。 您可以使用Java的Scanner来破解它,有更好的方法吗?

为什么不使用正则表达式来匹配您想要的字符串部分?

 [0-9] 

这就是你所需要的,加上它需要的任何周围的字符。

请查看http://www.regular-expressions.info/tutorial.html以了解正则表达式的工作原理。

编辑:我想说Regex对于这个例子可能有点过分,如果其他提交者发布的代码确实有效……但我仍然建议学习正则表达式,因为它们非常强大,并且比我愿意承认的更方便(在等了好几年才给他们开枪)。

如前所述,请尝试使用正则表达式。 这应该有助于:

 String value = "Hello123"; String intValue = value.replaceAll("[^0-9]", ""); // returns 123 

然后你只需从那里转换为int(或整数)。

我相信你可以这样做:

 Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+"); int integer = in.nextInt(); 

编辑:添加了Carlos的useDelimiter建议

假设你想要一个尾随数字,这将有效:

 import java.util.regex.*; public class Example { public static void main(String[] args) { Pattern regex = Pattern.compile("\\D*(\\d*)"); String input = "Hello123"; Matcher matcher = regex.matcher(input); if (matcher.matches() && matcher.groupCount() == 1) { String digitStr = matcher.group(1); Integer digit = Integer.parseInt(digitStr); System.out.println(digit); } System.out.println("done."); } } 

我一直认为迈克尔的正则表达式是最简单的解决方案,但是如果你使用Matcher.find()而不是Matcher.matches(),第二个想法只是“\ d +”有效:

 import java.util.regex.Pattern; import java.util.regex.Matcher; public class Example { public static void main(String[] args) { String input = "Hello123"; int output = extractInt(input); System.out.println("input [" + input + "], output [" + output + "]"); } // // Parses first group of consecutive digits found into an int. // public static int extractInt(String str) { Matcher matcher = Pattern.compile("\\d+").matcher(str); if (!matcher.find()) throw new NumberFormatException("For input string [" + str + "]"); return Integer.parseInt(matcher.group()); } } 

虽然我知道这是一个6岁的问题,但我现在正在为那些想要避免学习正则表达式的人发布答案(你应该这样做)。 这种方法也给出了数字之间的数字(例如,HP 123 KT 567将返回123567)

  Scanner scan = new Scanner(new InputStreamReader(System.in)); System.out.print("Enter alphaNumeric: "); String x = scan.next(); String numStr = ""; int num; for (int i = 0; i < x.length(); i++) { char charCheck = x.charAt(i); if(Character.isDigit(charCheck)) { numStr += charCheck; } } num = Integer.parseInt(numStr); System.out.println("The extracted number is: " + num);