Search code examples
javaregexreplaceall

Java Regular Expression : Need Simpler Solution


I am new to regular expressions. I have a string named encryptId (does not contain |) and I want to append the | character after every 20 characters of this string, using the encryptId.replace/replaceAll(Regex,Pattern) function in Java. But it should never have \ at the end of the string.

Thanks for your help.

EDIT:

  1. The reason I want to use replace and replaceAll functions particularly is because I have to use that in velocity template mananger. And there we can use common String functions but can't write whole java code.

  2. My current solution is shown below

encryptId = encryptId.replaceAll("(.{20})","$1|");
if(encryptId.charAt(encryptId.length() - 1)=='|') {
    encryptId = encryptId.substring(0,encryptId.length()-1);
}

I need to get rid of this if statement so that It would be just a string function.


Solution

  • This can be done via regular expressions as follows

    static String enterADelimiter(String str, String delimiter, int after) {
            String regex = "(.{" + after +"})(?!$)";
            String replacement = "$1" + delimiter;
    
            return str.replaceAll(regex, replacement);
        }
    

    Just use

    enterADelimiter(yourString, "|", 20)
    

    This will return correct solution. Explantion

    (            Start group 1
      .          Match Anything
      {after}    after times
    )            End group 1
    (?!$)        Don't match if at end of String