gpt4 book ai didi

Java 通过替换特殊字符来转换一组字符串

转载 作者:行者123 更新时间:2023-11-30 06:48:43 25 4
gpt4 key购买 nike

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]

最佳答案

您可以将拆分与 * 一起使用,然后您可以处理每个元素,例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com