pol*_*nts 12
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", ""));
// i == 1234
Run Code Online (Sandbox Code Playgroud)
请注意这将如何将来自字符串不同部分的数字"合并"为一个数字.如果你只有一个数字,那么这仍然有效.如果您只想要第一个数字,那么您可以这样做:
int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1"));
// i == -42
Run Code Online (Sandbox Code Playgroud)
正则表达式有点复杂,但在使用Integer.parseInt
解析为整数之前,它基本上用它包含的第一个数字序列(带有可选的减号)替换整个字符串.
使用以下RegExp(请参阅http://java.sun.com/docs/books/tutorial/essential/regex/):
\d+
Run Code Online (Sandbox Code Playgroud)
通过:
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11608 次 |
最近记录: |