我有类似“ali123hgj”的东西。我想要123整数。我怎样才能在java中创建它?
答案 0 :(得分:11)
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", ""));
// i == 1234
请注意这将如何将字符串不同部分的数字“合并”为一个数字。如果你只有一个数字,那么这仍然有效。如果你只想要第一个数字,那么你可以这样做:
int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1"));
// i == -42
正则表达式有点复杂,但在使用Integer.parseInt
解析为整数之前,它基本上用它包含的第一个数字序列(带有可选的减号)替换整个字符串。
答案 1 :(得分:8)
使用以下RegExp(请参阅http://java.sun.com/docs/books/tutorial/essential/regex/):
\d+
人:
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
}
答案 2 :(得分:1)
String alphanumeric = "12ABC34def";
String digits = CharMatcher.JAVA_DIGIT.retainFrom(alphanumeric); // 1234
String letters = CharMatcher.JAVA_LETTER.retainFrom(alphanumeric); // ABCdef
如果您只想匹配ASCII数字,请使用
String digits = CharMatcher.inRange('0', '9').retainFrom(alphanumeric); // 1234
如果您只想匹配拉丁字母的字母,请使用
String letters = CharMatcher.inRange('a', 'z')
.or(inRange('A', 'Z')).retainFrom(alphanumeric); // ABCdef
答案 3 :(得分:0)
您可以按照以下方式进行:
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)));
}
它也很容易适应多个数字组。该代码仅用于定位:它尚未经过测试。
答案 4 :(得分: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...
}
答案 5 :(得分:0)
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;
输入“asg123d ddhd-2222-33sds --- --- 222 ss --- 33dd 234”会产生此输出 [123,-2222,-33,-222,-33,234]