replaceAll 替换所有与提供的正则表达式不匹配的内容
replaceAll to replace everything which doesn't match the provided regex
字符串 class 中的方法 replaceAll(String regex, String replacement)
将此字符串中与给定正则表达式匹配的每个子字符串替换为给定的替换项。是否可以否定正则表达式以便替换所有不匹配的内容?
例如,我有一个在方括号内带有子字符串的字符串(没有嵌套括号,字符串的其余部分既不包含左方括号也不包含右方括号)
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 + "$).*", "")
我通过搜索 "negate regex" 找到的这个和其他一些对我不起作用。
预期输出为 test = "keep this"
你很接近你可以像这样使用replaceAll
,像这样与组一起使用;
test = test.replaceAll(".*\[(.*?)\].*", "");
更具体一点,但为什么不循环模式:
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();
字符串 class 中的方法 replaceAll(String regex, String replacement)
将此字符串中与给定正则表达式匹配的每个子字符串替换为给定的替换项。是否可以否定正则表达式以便替换所有不匹配的内容?
例如,我有一个在方括号内带有子字符串的字符串(没有嵌套括号,字符串的其余部分既不包含左方括号也不包含右方括号)
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 + "$).*", "")
我通过搜索 "negate regex" 找到的这个和其他一些对我不起作用。
预期输出为 test = "keep this"
你很接近你可以像这样使用replaceAll
,像这样与组一起使用;
test = test.replaceAll(".*\[(.*?)\].*", "");
更具体一点,但为什么不循环模式:
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();