在java中的字符串数字
答
使用下面的正则表达式(见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
}
答
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", ""));
// i == 1234
注意这将如何 “合并”,从字符串的不同部分的数字连成一个号码。如果你只有一个号码,那么这仍然有效。如果你只想要第一个数字,那么你可以做这样的事情:
int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1"));
// i == -42
的正则表达式是有点复杂,但它基本上取代了整个字符串的数字的第一序列,它包含(带有可选减号),然后使用Integer.parseInt
解析为整数。
答
你也许可以做到这一点沿着这些线路:
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;
输入 “asg123d DDHD-2222-33sds --- --- 222个--- SS 234 33dd” 的结果在这个输出中 [123,-2222,-33,-222, - 33,234]
答
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
“abc123def567ghi”或“abcdef”'? – kennytm 2010-04-04 14:01:55
你总是有3个字符之前的数字或它只是一个例子? – lbedogni 2010-04-04 14:02:10
它不只是三个字符,它是0或更多字符之间的数字。它可以是“123”,“sdfs”,“123fdhf”,“fgdkjhgf123” – 2010-04-04 14:09:03