Java正则表达式除了符号组合

时间:2014-12-21 12:37:45

标签: java regex

我试图找到包含任何字符的字段,但不包括组合" [%"

例如:

Input: atrololo[%trololo
Output: atrololo

Input: tro[tro%tro[%trololo
Output: tro[tro%tro

我已经写了正则表达式,除了[或%:

之外的任何符号
[A-Za-z-0-9\s!-$-&/:-@\\-`\{-~]*

我必须在表达方式的末尾添加类似[^("[%")]的内容,但我无法解决它应该如何输入。

您可以查看我的常规

https://www.regex101.com/

将测试字符串作为:

sdfasdsdfasa#@!55@321!2h/ хf[[[[[sds d
asgfdgsdf[[[%for (int i = 0; i < 5; i++){}%]
[% fo%][%r(int i = 0; i < 5; i++){ %]*[%}%]
[%for(int i = 0; i < 5; i++){%][%=i%][%}%]
[%@n%]<[%@ n + m %]*[%@%]>[%@%]
%?s.equals(""TEST"")%]TRUE[%@3%]![%@%][%?%]

亲切的问候。

2 个答案:

答案 0 :(得分:3)

你可以使用如下所示的负前瞻正则表达式来获取[%之前的部分

^(?:(?!\[%).)*

(?:(?!\[%).)*匹配任何字符,但不匹配[%零次或多次。

DEMO

String s = "tro[tro%tro[%trololo";
Pattern regex = Pattern.compile("^(?:(?!\\[%).)*");
 Matcher matcher = regex.matcher(s);
 while(matcher.find()){
        System.out.println(matcher.group());  // output : tro[tro%tro
}

基于前瞻性的正则表达式,

^.*?(?=\[%)

DEMO

Pattern regex = Pattern.compile("^.*?(?=\\[%)");

您可以根据正则表达式\[%拆分输入字符串并获取所需的部分。

String s = "tro[tro%tro[%trololo";
String[] part = s.split("\\[%");
System.out.println(part[0]);  // output : tro[tro%tro

答案 1 :(得分:1)

使用输入/输出对作为规范:

String input; // the starting string
String output = input.replaceAll("\\[%.*", "");