3.将A1B2C3D4E5F6G7H8拆分开来,并分别存入int[]和String[]数组。得到的结果为[1,2,3,4,5,6,7,8]和[A,B,C,D,E,F,G,H]。
import java.util.*;
import java.util.regex.*;
import java.io.*;
public class Test
{
public static void main(String[] args) throws Exception
{
//存储用的数组
int[] nums = new int[8];
String[] strs = new String[8];
//记录位置
int n = 0;
int s = 0;
//开始解析文本
String str = "A1B2C3D4E5F6G7H8";
Pattern p1 = Pattern.compile("\\d");//匹配数字
Matcher m1 = p1.matcher(str);
while(m1.find())
{
nums[n++] = Integer.parseInt(m1.group());
}
System.out.println(Arrays.toString(nums));
p1 = Pattern.compile("\\D"); //匹配字母
m1 = p1.matcher(str);
while(m1.find())
{
strs[s++] = m1.group();
}
System.out.println(Arrays.toString(strs));
}
}
2021年12月24日
以下才是正解,上面的方法是复杂化了,只需要使用String的split()方法结合正则表达式即可
public class Test
{
public static void main(String[] args)
{
String str = "A1B2C3D4E5F6G7H8";
String[] nums = str.split("\\D");
int[] nums2 = new int[nums.length-1];
for(int i = 1 ; i < nums.length; i++)
{
nums2[i-1] = Integer.valueOf(nums[i]);
}
System.out.println(Arrays.toString(nums2));
String[] words = str.split("\\d");
System.out.println(Arrays.toString(words));
}
}
2021年12月25日
下面的解法也比第一种要好得多
import java.util.*;
import java.util.regex.*;
public class Test
{
public static void main(String[] args)
{
String str = "a1b2c3d4e5";
p = Pattern.compile("\\d");
System.out.println(Arrays.toString(p.split(str)));
p = Pattern.compile("\\D");
System.out.println(Arrays.toString(p.split(str)));
}
}