0

My string is "test" "test" has 4 characters I want to replace "test" with "****" so I get "****"

My code

System.out.println("_test_");
System.out.println("_test_".replaceAll("test", "*"));

But it replace test with 1 *.

Saad A
  • 1,135
  • 2
  • 21
  • 46

5 Answers5

3

If the word test is just an example, you may use Matcher.appendReplacement (see How to appendReplacement on a Matcher group instead of the whole pattern? for more details on this technique):

String fileText = "_test_";
String pattern = "test";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(fileText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, repeat("*", m.group(0).length()));
}
m.appendTail(sb); // append the rest of the contents
System.out.println(sb);

And the repeat function (borrowed from Simple way to repeat a String in java, see other options there) SO post is:

public static String repeat(String s, int n) {
    if(s == null) {
        return null;
    }
    final StringBuilder sb = new StringBuilder(s.length() * n);
    for(int i = 0; i < n; i++) {
        sb.append(s);
    }
    return sb.toString();
}

See IDEONE demo

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • There's also the [StringUtils.repeat](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#repeat) that could help :-) – Enissay Feb 01 '16 at 21:06
  • That is why I added the link to the SO question I borrowed the method from. I used this one for **demo only**, since I cannot use StringUtils on IDEONE. – Wiktor Stribiżew Feb 01 '16 at 21:07
0

Yes, because replaceAll(str1, str2) will replace all occurrences of str1 with str2. Since you are using literals, you need to say

System.out.println("_test_".replaceAll("test", "****"));

If you want your own replacement function you can do something like this:

public static String replaceStringWithChar(String src, String seek, char replacement)
{
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < seek.length(); i++) sb.append(replacement);
    return src.replaceAll(seek, sb.toString());
}

You would then call it like so:

replaceStringWithChar("_test_", "test", '*');
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
  • This is a misunderstanding of the question, OP is really asking given a string of any arbitrary length, he wants to replace that entire word with stars. ```Test``` was just an example of a string with 4 letters in. – DominicEU Feb 01 '16 at 21:05
0

If you have an arbitrary text to be replaced, and you want to use replaceAll(), be aware that it takes a regular expression, and various characters have special meaning. To prevent issues, call Pattern.quote().

Also, to replace with a sequence of * of equal length, you need to build a string of such.

Here is a nice short method for doing it:

private static String mask(String input, String codeword) {
    char[] buf = new char[codeword.length()];
    Arrays.fill(buf, '*');
    return input.replaceAll(Pattern.quote(codeword), new String(buf));
}

Test

System.out.println(mask("_test_", "test"));
System.out.println(mask("This is his last chance", "is"));

Output

_****_
Th** ** h** last chance
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

So I got the answer and I was really looking for something with as few line as possible. Thank you all for the answer but this is the answer I found most useful.

I apologize for not being clear in the question, if I was not.

String str1 = "_AnyString_";
int start_underscore = str1.indexOf("_");
int end_underscore = str1.indexOf("_", start_underscore + 1);
String str_anything = str1.substring(start_underscore + 1, end_underscore);
String str_replace_asterisk = str_anything.replaceAll(".", "*");
System.out.println(str_replace_asterisk);
str1 = str1.replace(str_anything, str_replace_asterisk);
System.out.println(str1);

Output:

_AnyString_
_*********_
Saad A
  • 1,135
  • 2
  • 21
  • 46
-1

Actually you are pretty close the what you want. This is what you can do:

System.out.println("_test_".replaceAll("[test]", "*"));
System.out.println("hello".replaceAll("[el]", "*"));

Output:

_****_
h***o
user3437460
  • 17,253
  • 15
  • 58
  • 106
  • Not good, since `"hello".replaceAll("[test]", "*")` would produce `h*llo`, replacing the `e` even though the string doesn't contain `test`. – Andreas Feb 01 '16 at 22:10
  • @Andreas OP didn't say he wants the entire text sequence which match to be replaced. – user3437460 Feb 02 '16 at 08:15