简体   繁体   中英

replace String with another in java using regular Expression

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM