提取字符串的整数部分(如
)的最佳方法是什么Hello123
你如何获得123部分。您可以使用Java的Scanner来破解它,有更好的方法吗?
答案 0 :(得分:28)
如前所述,请尝试使用正则表达式。这应该有所帮助:
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
然后你只需将它从那里转换为int(或整数)。
答案 1 :(得分:24)
我相信你可以这样做:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
编辑:添加了Carlos的useDelimiter建议
答案 2 :(得分:8)
为什么不直接使用正则表达式来匹配您想要的字符串部分?
[0-9]
这就是你所需要的,加上它所需要的任何周围的字符。
查看http://www.regular-expressions.info/tutorial.html以了解正则表达式的工作原理。
编辑:我想说Regex对于这个例子可能有点过分,如果确实是其他提交者发布的代码有效......但我仍然建议学习正则表达式,因为它们非常功能强大,并且会比我想承认的更方便(在等了好几年之后才给他们开枪)。
答案 3 :(得分:4)
假设您想要一个尾随数字,这将有效:
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.");
}
}
答案 4 :(得分:4)
我一直认为迈克尔的正则表达式是最简单的解决方案,但是如果使用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());
}
}
答案 5 :(得分:3)
虽然我知道这是一个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);
答案 6 :(得分:0)
private JSONObject queryResults;
...
...
String finalResults = "";
JSONArray results = queryResults.getJSONArray("results");
for(int i = 0; i < results.length(); i++){
JSONObject item = results.getJSONObject(i);
finalResults += item.getString("definition") + " ";
}
答案 7 :(得分:0)
这很适合我。
const ColoredH1 = styled(H1)`
/* color: "black"; */ /* Invalid Color */
color: black; /* Valid Color */
color: ${"black"} /* Or use a valid color representation as String */
`;
输出:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("string1234more567string890");
while(m.find()) {
System.out.println(m.group());
}