1。通过rex:("\\d+")来提取字符串
Scanner sc = new Scanner(System.in);
String[] a = sc.nextLine().split("\\d+");
for(String s : a){
System.out.print(s+" ");
}
2。通过rex: [^0-9] 来提取数字
Scanner sc = new Scanner(System.in);
//String[] a = sc.nextLine().split("\\d+");
Pattern pattern = Pattern.compile("[^0-9]");
String a = sc.nextLine();
Matcher a1 = pattern.matcher(a);
//System.out.println(a1.replaceAll(" "));
String[] dis = a1.replaceAll(" ").split("\\s+"); //到这儿为为止已经提取了数子串
//====下面输出数字串中最大的一个
int temp = 0;
for(int i = 0; i < dis.length-1; i++){
if(dis[i].length() < dis[i+1].length()){
temp = i+1;
}
}
System.out.println(dis[temp]);
本文介绍如何在Java中使用正则表达式提取字符串中的数字,并演示了两种不同的方法实现这一功能。首先展示了如何通过split方法分割非数字字符来获取数字字符串,接着介绍了如何利用Pattern和Matcher类来匹配并提取所有数字,最后输出这些数字中长度最长的一个。

662

被折叠的 条评论
为什么被折叠?



