public static void main(String[] args) {
String str = "astv*12atthh124ggh*dhr1234sfff123*dgdfg1234*mnaoj";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
List<String> strings = new ArrayList<String>();
List<Integer> nums = new ArrayList<Integer>();
while (m.find()) {
nums.add(Integer.parseInt(m.group()));
}
p = Pattern.compile("[a-z]+");
m = p.matcher(str);
while (m.find()) {
strings.add(m.group());
}
System.out.println(nums);
System.out.println(strings);
}
输出:
[12, 124, 1234, 123, 1234]
[astv, atthh, ggh, dhr, sfff, dgdfg, mnaoj]
但我想要像这样的输出:
[12124, 1234123, 1234]
[astv, atthhggh, dhrsfff, dgdfg, mnaoj]
最佳答案
您可以将 split 与 *
一起使用,然后您可以使用每个元素,例如:
public static void main(String[] args) {
String str = "astv*12atthh124ggh*dhr1234sfff123*dgdfg1234*mnaoj";
String[] spl = str.split("\\*");//[astv, 12atthh124ggh, dhr1234sfff123, dgdfg1234, mnaoj]
List<String> strings = new ArrayList<>();
List<Integer> nums = new ArrayList<>();
for (String s : spl) {
String tmp = s.replaceAll("\\d+", "");//replace all the digits with empty
if (!tmp.trim().isEmpty()) {
strings.add(tmp);
}
tmp = s.replaceAll("[a-z]+", "");//replace all the character with empty
if (!tmp.trim().isEmpty()) {
nums.add(Integer.parseInt(tmp));
}
}
System.out.println(nums);
System.out.println(strings);
}
输出
[12124, 1234123, 1234]
[astv, atthhggh, dhrsfff, dgdfg, mnaoj]
Ideone demo
关于Java通过替换特殊字符来转换一组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43916170/