如何在每次更改的正则表达式中添加一个字符?

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;
}

其实我是用上面的方法统计每个字符的

我想在正则表达式中使用 s.charAt(i) 以便它计数并显示如下。但是我知道那行(第 10 行)行不通。

如果可以的话我该怎么做?

示例:

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

Java没有string interpolation,所以写在字符串字面量里面的代码不会被执行;它只是字符串的一部分。您需要执行类似 "[" + s.charAt(i) + "]" 的操作,而不是以编程方式构建字符串。

但是当字符是正则表达式特殊字符时,例如^,这是有问题的。在这种情况下,字符 class 将是 [^],它完全匹配任何字符。您可以在构建正则表达式时转义正则表达式特殊字符,但这过于复杂。

因为你只是想替换一个精确的子字符串,所以使用 replace method which does not take a regex. Don't be fooled by the name replace vs. replaceAll; both methods replace all occurrences 更简单,不同之处在于 replaceAll 使用正则表达式而 replace 只使用确切的子串。例如:

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