回答(13)
2 years ago
在Java 1.4及更高版本中:
String input = "...";
Matcher matcher = Pattern.compile("[^0-9]+([0-9]+)[^0-9]+").matcher(input);
if (matcher.find()) {
String someNumberStr = matcher.group(1);
// if you need this to be an int:
int someNumberInt = Integer.parseInt(someNumberStr);
}
2 years ago
看看你可以使用StringTokenizer来做到这一点
String str = "as:"+123+"as:"+234+"as:"+345;
StringTokenizer st = new StringTokenizer(str,"as:");
while(st.hasMoreTokens())
{
String k = st.nextToken(); // you will get first numeric data i.e 123
int kk = Integer.parseInt(k);
System.out.println("k string token in integer " + kk);
String k1 = st.nextToken(); // you will get second numeric data i.e 234
int kk1 = Integer.parseInt(k1);
System.out.println("new string k1 token in integer :" + kk1);
String k2 = st.nextToken(); // you will get third numeric data i.e 345
int kk2 = Integer.parseInt(k2);
System.out.println("k2 string token is in integer : " + kk2);
}
由于我们将这些数值数据转换为三个不同的变量,我们可以在代码中的任何位置使用此数据(以供进一步使用)
2 years ago
除了Pattern之外,Java String类还有几个可以使用正则表达式的方法,在这种情况下代码将是:
"ab123abc".replaceFirst("\\D*(\\d*).*