如何使用java replaceAll(regex,replacement)方法掩盖字符串中的最后一个括号括号?

时间:2017-02-07 11:09:42

标签: java regex replaceall

我想

ASDFASDFG => A********
(qwe)rtya(sdfg)h => (qwe)rtya(s***)h

所以我试着

public String setMask_ (String name_){

    String result = null;

    if(name_.lastIndexOf("(") > -1) {
        // Bracket Begin 
        int locBrkBgn = name_.lastIndexOf("(") +2;
        // Bracket End 
        int locBrkEnd = locBrkBgn + (name_.substring(locBrkBgn, name_.length())).indexOf(")") -1;
        // result = name_.replaceAll("(?<=.{"+locBrkBgn+"}).*(?={"+locBrkEnd+"})", "*");
        result = name_.replaceAll("(?<=\\().*?(?=\\))", "*");
    } else {
        result = name_.replaceAll("(?<=.{1}).", "*");
    }
    return result;
}

2 个答案:

答案 0 :(得分:1)

哦,我想我做到了。

public String setMask_ (String name_){

    String result = null;

    if(name_.lastIndexOf("(") > -1) {
        // locate. Bracket Begin 
        int locBrkBgn = name_.lastIndexOf("(") +2;
        result = name_.replaceAll("(?<=.{"+locBrkBgn+"}).(?=[^\\)]*?\\))", "*");
    } else {
        result = name_.replaceAll("(?<=.{1}).", "*");
    }
    return result;
}

答案 1 :(得分:0)

result = name_.replaceAll(“\(\ w + \)\ w * $”,“(”+ name_.replaceAll(“\(\ w \)\ w * \(\ w * \)“,”)“));

基本上,用*替换第二个括号内的部分,然后用闭括号括号替换所有内容直到最后一个右括号。