如何最好地从字符串中提取整数部分?
Hello123
如何获取123部分?你可以使用Java的Scanner进行一些技巧性操作,不过有没有更好的方法呢?
如何最好地从字符串中提取整数部分?
Hello123
如何获取123部分?你可以使用Java的Scanner进行一些技巧性操作,不过有没有更好的方法呢?
如前所述,请尝试使用正则表达式。这应该会有所帮助:
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
然后你只需要将其转换为 int(或 Integer)即可。
我相信你可以这样做:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
编辑:Carlos提出了使用useDelimiter的建议
nextInt
的文档说明:“如果下一个标记无法转换为有效的整数,则此方法将抛出 InputMismatchException”,这适用于 Hello123
。可以使用 in.useDelimiter("[^0-9]+");
来忽略非数字。 - user85421为什么不直接使用正则表达式来匹配您想要的字符串部分呢?
[0-9]
那就是你需要的全部内容,再加上它所需的任何周围字符。
查看http://www.regular-expressions.info/tutorial.html以了解正则表达式的工作原理。
编辑:我想说,对于这个示例,正则表达式可能有点过头了,如果另一个提交者发布的代码确实有效...但我仍然建议普遍学习正则表达式,因为它们非常强大,并且将比我愿意承认的更有用(在尝试了多年之后)。
虽然我知道这是一个6年前的问题,但我为那些想要避免现在学习正则表达式的人提供一个答案(你应该学习)。这种方法还可以返回数字之间的数字(例如,HP123KT567将返回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);
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.");
}
}
一开始我认为Michael的正则表达式是可能最简单的解决方案,但仔细想了想,只需要使用"\d+"并使用Matcher.find()而不是Matcher.matches()即可:
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());
}
}
这个对我完美地起作用了。
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("string1234more567string890");
while(m.find()) {
System.out.println(m.group());
}
输出:
1234
567
890
String[] parts = s.split("\\D+"); //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
}
String str= "HEll1oTe45st23";
String intValue = str.replaceAll("[^0-9]", "");
System.out.print(Integer.parseInt(intValue));