import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test{
public static void main(String[] args){
String str = "234KB";
//保存分离数字的集合
List<String> list = new ArrayList<String>();
//分离英语和数字
String s = "\\d+.\\d|\\w+";
Pattern pattern = Pattern.compile(s);
Matcher ma = pattern.matcher(str);
while(ma.find()){
list.add(ma.group());
}
//取出数字
for(int i = 0;i < list.size();i++){
if(i == 0){
System.out.println("分离后的数字为: " + list.get(i));
}else{
System.out.println("分离后的英文为: " + list.get(i));
}
}
}
}
第二种方法:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ElTest{
public static void main(String[] args){
String str = "234KB";
String s = "\\d+.\\d|\\w+"; //分离英语和数字
Pattern pattern = Pattern.compile(s);
Matcher ma = pattern.matcher(str);
if(ma.find()){
System.out.println(ma.group()); //数字
System.out.println(str.replace(ma.group(),"")); //英文字母
}
}
}