1

In Java, I have to wrap a string value to another using RegEx and function replace.

Example #1: What will replace "123C5" (5 characters) with "*****"?

Example #2: What will replace "12354CF5214" (11 characters) with "*******5214"? replace only the first 7 characters

Currently, i am using this function but i need to optimize it :

public  String getMaskedValue(String value) {

    String maskedRes = "";
    if (value!=null && !value.isEmpty()) {
        maskedRes = value.trim();
        if (maskedRes.length() <= 5) {
            return maskedRes.replaceAll(value, "$1*");
        } else if (value.length() == 11) {
            return maskedRes.replace(value.substring(0, 7), "$1*");
        }
    }
    return maskedRes;
}

can anyone help me please ? thank you for advanced

1
  • 1
    Why use regexp at all? Substring the text and prepend the "******". Also, you should really explain WHY you need to optimize it, and in which way (execution speed? lines of code?), as the current version is not that bad. Commented Apr 22, 2020 at 12:12

1 Answer 1

2

You may use a constrained-width lookbehind solution like

public static String getMaskedValue(String value) {
    return value.replaceAll("(?<=^.{0,6}).", "*");
}

See the Java demo online.

The (?<=^.{0,6}). pattern matches any char (but a line break char, with .) that is preceded with 0 to 6 chars at the start of the string.

A note on the use of lookbehinds in Java regexps:

✽ Java accepts quantifiers within lookbehind, as long as the length of the matching strings falls within a pre-determined range. For instance, (?<=cats?) is valid because it can only match strings of three or four characters. Likewise, (?<=A{1,10}) is valid.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.