我想在我的正则表达式表达式之前添加“!”。 我有:
TASK PERS asdf
PERS asdf
我想使用正则表达式并获取
! TASK PERS asdf
! PERS asdf
我不知道怎么写正则表达式:(我试了很多次,...但我失败了,你能帮帮我吗?
Java
newContent = content.replaceAll("[A-Z]*TASK PERS", "!TASK PERS")
但它不起作用。
最佳答案
非正则表达式方法对于这项任务会好得多,但如果我们想用表达式来处理,这可能会起作用:
(TASK PERS|PERS)(.*)
并将其替换为! $1$2
Demo
测试
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(TASK PERS|PERS)(.*)";
final String string = "TASK PERS asdf\n"
+ "PERS asdf\n"
+ "TASK PERS asdf\n"
+ "PERS asdf";
final String subst = "! \\1\\2";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
正则表达式电路
jex.im可视化正则表达式:
关于java - 前面有字母的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529314/