I want to use replace all characters that do not match the word => bac [0-9], if someone can help Edit
I tried :
String test = "bac 5 - and plus";
test = test.replaceAll("^(?!.*bac \\ [0-9]).*","")
===>I want result test = "bac 5"
CodePudding user response:
Use a look behind:
test = test.replaceAll("(?<=bac \\ \\d).*","");
CodePudding user response:
Your pattern with the negative lookahead ^(?!.*bac \ [0-9]).* means to match the whole line if it does not contain this pattern bac \ [0-9]
You can use a capture group instead for the part that you want to keep, and match the rest of the line that should be removed.
In the replacement, use group 1 with $1
String test = "bac 5 - and plus";
test = test.replaceAll("(bac \\ \\d).*","$1");
System.out.println(test);
Output
bac 5
