gpt4 book ai didi

java - 如何将字符串中的所有数字移动到字符串的开头?

转载 作者:搜寻专家 更新时间:2023-10-30 19:48:03 25 4
gpt4 key购买 nike

对于以下字符串:

String str="asd14sd67fgh007";

我想要这样的输出:

1467007asdsdfgh

我知道如何分割一个字符串,但我不知道如何得到它。对于拆分,我有这段代码:

public static void main(String[] args) {
String str="asd14sd67fgh007";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}
}

最佳答案

2 replaceAll() 可以做到(如果你真的想使用正则表达式:P):

public static void main(String[] args) {
String s= "asd14sd67fgh007";
String correctedString = s.replaceAll("\\D+", "") + s.replaceAll("\\d+", "");
System.out.println(correctedString);
}

订单:

1467007asdsdfgh

注意:

"\\D+" ==> replace all non-numeric characters with "". (will give you all numbers).

"\\d+" ==> replace all digits with "" (will give you all non-numeric characters)

关于java - 如何将字符串中的所有数字移动到字符串的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33783151/

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