replaceAll to replace everything which doesn't match the provided regex

Trillian :

The method replaceAll(String regex, String replacement) from string class replaces each substring of this string that matches the given regular expression with the given replacement. Is it possible to negate the regex so that everything which doesn't matches is replaced?

For example I've a string with a substring inside square brackets (No nested brackets and rest of string doesn't contain neither opening nor closing square brackets)

String test = "some text [keep this] may be some more ..";

I've found a regex to extract the substring between []:

String test = "some text [keep this] may be some more ..";        
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(test);

while(m.find()) {
    test = m.group(1);
}

What I want to do is, if possible, to use the replaceAll method with somehow negated regex to replace everything which doesn't match the above regex.

String regex = "\\[(.*?)\\]";
test.replaceAll("(?!" + regex + "$).*", "")

This and some others, which i found by searching for "negate regex" didn't work for me.

Expected output is test = "keep this"

YCF_L :

You are close you can use replaceAll like so, with group like so ;

test = test.replaceAll(".*\\[(.*?)\\].*", "$1");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141756&siteId=1