1

Can i use a regex to replace the 4th, 5th, 6th words with * from a string ?

Actually i do this:

public class Test
{
    public static void main( String[] args )
    {
        StringBuilder myName = new StringBuilder("AD-BJR5U");
        myName.setCharAt(3, '*');
        myName.setCharAt(4, '*');
        myName.setCharAt(5, '*');
        System.out.println(myName);
    }
}

Input:

AD-BJR5U

Output:

AD-***5U

10
  • 3
    What is wrong with your current method? Commented Jul 25, 2017 at 8:31
  • Could you please show us sample input and expected output? Commented Jul 25, 2017 at 8:32
  • 4
    did you mean words or letters? Commented Jul 25, 2017 at 8:33
  • 1
    Much more clearer and human-understandable. I don't think the same. Commented Jul 25, 2017 at 8:33
  • 1
    If you want to improve your code then you have to extract this functionality into method or just use builder.replace(3, 6, "***"); Commented Jul 25, 2017 at 8:38

3 Answers 3

4

Your current approach is very clear and straight forward I'd go with that if I were you. Anyway Regular Expressions are an option:

(?<=^(?:.{3}|.{4}|.{5})).

Java live demo

Sign up to request clarification or add additional context in comments.

Comments

3

Following the example you give, I will answer something like that:

// Keeping 3 firsts char; will replace the 3 of the center, and keep all to the end
^(.{3}).{3}(.*)$

So in Java:

str.replaceAll("^(.{3}).{3}(.*)$", "$1***$2");

Comments

2

You can try with replace(int start, int end, String str) method of StringBuilder

myName.replace(3, 6, "***");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.