方法replaceAll(String regex, String replacement) from string类将此字符串中与给定正则表达式匹配的每个子字符串替换为给定的替换。有没有可能否定正则表达式,以便替换所有不匹配的内容?
例如,我有一个将子字符串放在方括号中的字符串(没有嵌套的括号,字符串的其余部分既不包含左方括号,也不包含右方括号)
String test = "some text [keep this] may be some more ..";我找到了一个正则表达式来提取[]之间的子字符串:
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);
}我想要做的是,如果可能的话,使用带有某种否定正则表达式的replaceAll方法来替换与上面的正则表达式不匹配的所有内容。
String regex = "\\[(.*?)\\]";
test.replaceAll("(?!" + regex + "$).*", "")我通过搜索“否定正则表达式”找到的这个和其他一些东西对我不起作用。
预期输出为test = "keep this"
发布于 2019-09-09 23:45:46
你很接近,你可以像这样使用replaceAll,像这样使用群组;
test = test.replaceAll(".*\\[(.*?)\\].*", "$1");发布于 2019-09-09 23:54:01
稍微间接一点,但为什么不在模式上循环:
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();https://stackoverflow.com/questions/57857170
复制相似问题