1

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.

7
  • 1
    Why do you want to use replace or replaceAll particularly? I think it'd be much easier to do using a StringBuilder. Commented Nov 26, 2015 at 16:33
  • 1
    you need a simpler solution? show us your current solution. Commented Nov 26, 2015 at 16:33
  • @PhilippSander , I specify that solution in EDIT. Commented Nov 26, 2015 at 18:25
  • @ArunBhati What is the problem with the second part? Is the problem that you can't use substring or that you can't use charAt? Commented Nov 26, 2015 at 18:34
  • @PaulBoddington, It's just that I think from regular expression itself we can remove if statement. Commented Nov 26, 2015 at 18:37

4 Answers 4

1

You asked how to do it with replaceAll: I say don't. Regular expressions are not always the best approach to string manipulation problems.

You can efficiently build the new string by taking 20 character blocks from encryptId and appending them to a StringBuilder, optionally appending the pipe if it will not be at the end of the string:

String method(String encryptId) {
  StringBuilder sb = new StringBuilder(encryptId.length() + encryptId.length() / 20);
  for (int i = 0; i < encryptId.length(); i += 20) {
    int end = Math.min(i + 20, encryptId.length());
    sb.append(encryptId, i, end);
    if (end != encryptId.length()) {
      sb.append('|');
    }
  }
  return sb.toString();
}
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't compile, and after correcting the typos, | can be at the end of the string.
@PaulBoddington fixed. Thanks.
Upvoted since this is the most efficient solution here.
1

You can use String.toCharArray:

    String s = "..."; //your string
    int i = 0;
    StringBuilder res = new StringBuilder("");
    for (char c : s.toCharArray()){
        res.append(c);
        i++;
        if (i % 20 == 0 && i != s.length()){
            res.append("|");
        }
    }
    System.out.println(res.toString());

res will have your first String with an | every 20 characters but not at the end of the String.

2 Comments

Note that you want to avoid concatenating strings in loops, since it creates intermediate strings. It is more efficient to append the characters to a StringBuilder.
@AndyTurner I was not sure if the compiler would optimize this and use StringBuilders under the hood.
0

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 

4 Comments

Thanks @Aseem It worked. I upvoted your answer but It's not visible.
@Pirate_Jack Try again. Might work this time :D. You can accept the answer if it worked. The tick mark.
Ohh! It will be visible later as I don't have enough reputation so It will not be shown untill I get enough.
@Pirate_Jack I had completely forgotten that there was that limitation. But you should be able to accept it. See meta.stackexchange.com/questions/5234/… for how to.
0

Regex may complicate things more. You can also try to use StringBuilder for this:

        String encryptId = "test";
        StringBuilder builder = new StringBuilder(encryptId);

        int insertAfter = 20;
        for(int i = encryptId.length(); i > 0 ; i--) {
            if (i % insertAfter == 0 && i != encryptId.length()) {
                builder.insert(i, "|");
            }
        }

1 Comment

Note that inserting a character in the middle of a StringBuilder is quadratic, since it involves shifting up all of the following characters. source

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.