Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move all digits in a string to the beginning of the string?

Tags:

java

string

regex

For the following string:

String str="asd14sd67fgh007";

I want output like:

1467007asdsdfgh

I know how to split a string, but I don't know how to get this. For split, I have this code:

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());
    }
}
like image 389
Chanakya Avatar asked Nov 18 '15 14:11

Chanakya


People also ask

How do you move a space in a string in Java?

How can we move all the spaces of the String to the front using Java? This IDEONE will do it. Use the function trim(),ltrim(),rtrim() for remove the space from both size,left side,or right side.

How do you move special characters at the end of a string in Java?

To move all the special characters to the end of the given line, match all the special characters using this regex concatenate them to an empty string and concatenate remaining characters to another string finally, concatenate these two strings.


1 Answers

2 replaceAll() can do it (If you really want to use regex :P):

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

O/P :

1467007asdsdfgh

Note :

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

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

like image 152
TheLostMind Avatar answered Nov 01 '22 05:11

TheLostMind