正则表达式匹配所有内容,除了两个方括号之间的内容

时间:2020-04-14 14:18:28

标签: java regex

我进行了很多搜索,但没有找到我的具体情况。我需要一个正则表达式来匹配所有内容,除了两个尖括号之间的内容:

我找到了如何匹配除尖括号之外的所有内容: String regex="[^<>]*";

或如何匹配两个尖括号之间的内容: \<(.*?)\><([^>]+)>

那很好,但是我需要与之相反的事实。我尝试和^(否定)一起玩,但是没有成功。

例如: Fara Foo <not be selected>;another <also not be selected>

应返回: Fara Foo <>;another <>

整个事情应该在Java中工作。

更新:一个replaceAll(...)解决方案对我没有帮助,因为我想在replaceAll(...)调用中使用正则表达式:-)所以我真的需要正则表达式。 / p>

由于在评论中被询问: 在Java中,某些字符串操作(例如replaceAll()或split())直接采用正则表达式。使用PatternMatcher还有另一种方法。使用replaceAll()代替模式匹配器更为方便。这就是为什么我要使用“负”正则表达式来使用replaceAll ...

2 个答案:

答案 0 :(得分:1)

获得预期结果的一种方法是使用string.replaceAll去除尖括号之间的内容,例如:

String strIn = "Fara Foo <not be selected>;another <also not be selected>; ...";
String newStr = strIn.replaceAll("<([^>]+)>", "<>");

答案 1 :(得分:0)

您可以使用(?<=<)来跟踪<,然后使用(?=>)来跟踪>,而忽略了尖括号和右尖括号:

String input = "Fara Foo <not be selected>;another <also not be selected>; ...";
String regex = "(?<=<)([^>]*)(?=>)";
input = input.replaceAll(regex, "");

OUTPUTS:
Fara Foo <>;another <>; ...
相关问题