Search code examples
javaregexstringcharacterreplaceall

How can I add a character inside a Regular Expression which changes each time?


String s = scan.nextLine();

s = s.replaceAll(" ", "");

for (int i = 0; i < s.length(); i++) {
    System.out.print(s.charAt(i) + "-");
    int temp = s.length();

    // this line is the problem
    s = s.replaceAll("[s.charAt(i)]", '');

    System.out.print((temp - s.length()) + "\n");
    i = -1;
}

I was actually using the above method to count each character.

I wanted to use s.charAt(i) inside Regular Expression so that it counts and displays as below. But that line (line 10) doesn't work I know.

If it's possible how can I do it?

Example:

MALAYALAM (input)
          M-2
          A-4
          L-2
          Y-1

Solution

  • Java does not have string interpolation, so code written inside a string literal will not be executed; it is just part of the string. You would need to do something like "[" + s.charAt(i) + "]" instead to build the string programmatically.

    But this is problematic when the character is a regex special character, for example ^. In this case the character class would be [^], which matches absolutely any character. You could escape regex special characters while building the regex, but this is overly complicated.

    Since you just want to replace occurrences an exact substring, it is simpler to use the replace method which does not take a regex. Don't be fooled by the name replace vs. replaceAll; both methods replace all occurrences, the difference is really that replaceAll takes a regex but replace just takes an exact substring. For example:

    > "ababa".replace("a", "")
    "bb"
    > "ababa".replace("a", "c")
    "cbcbc"