简体   繁体   中英

Whitespace after n character and after every n-1 character following

I trying to create a regex for adding one whitespace after the n first character of a string and another one after every n-1 character following like this :

AZEOHNUEAOONA => AZEO HNU EAO ONA

MAIH31354ZEHIA212AE => MAIH 313 54Z EHI A21 2AE

Please can someone help me out? I have tried searching online for a similar problem, however it's very difficult to phrase it correctly in a search.

Edit : i using java 8

Try the following :)

class Sample {
    public static void main(String args[]){
        System.out.println(addSpaces("AZEOHNUEAOONA",4));
    }
    public static String addSpaces(String str,int n)
    {
        String reg = "(?<=.{" + n + "})(?=(.{"+ (n-1) + "})+$)";
        String rep = "$0 ";
        return str.replaceAll(reg,rep);
    }
}

Output:

AZEO HNU EAO ONA

The easiest way would be to use regular expressions only for one part of the problem. So basically, you split your string by taking the first n characters and then using the regular expressions on the remaining characters.

So basically, something like so:

    int n = 4;
    String str = "FOOOFOOFOOFOOFOO";
    String part1 = str.substring(0, n);
    String part2 = str.substring(n, str.length());
    System.out.println(part1 + " " + part2.replaceAll("(.{3})", "$1 ").trim());

Yields:

FOOO FOO FOO FOO FOO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM