简体   繁体   English

replaceAll替换与提供的正则表达式不匹配的所有内容

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

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. 从字符串类替换方法replaceAll(String regex, String 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. 我想要做的是,如果可能的话,使用replaceAll方法以某种方式否定正则表达式来替换与上述正则表达式不匹配的所有内容。

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" 预期输出是test = "keep this"

你很近,你可以像这样使用replaceAll像这样的组;

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

A bit more circumstantial, but why not loop over the pattern: 有点间接,但为什么不循环这个模式:

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(test);
StringBuilder sb = new StringBuilder();

// Java >= 9
m.replaceAll(mr -> sb.append(mr.group(1)));

// Java <= 8
while (m.find()) {
    sb.append(m.group(1));
}

String result = sb.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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