java - 前面有字母的正则表达式

标签 java regex

我想在我的正则表达式表达式之前添加“!”。 我有:

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可视化正则表达式:

enter image description here

关于java - 前面有字母的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529314/

相关文章:

c - 扩展正则表达式是否支持反向引用?

regex - Coldfusion ReReplace 电话号码重新格式化

java - 将 Tango 3D 点投影到屏幕 Google Project Tango

java - 在运行时将属于 JSON 对象一部分的 JSON 字符串转换为 JSON 对象

java - 将字节转换为位

java - 取数组的平均值

使用正则表达式的 Python 跨文件搜索

c# - 正则表达式替换多个组

java - Firebase查询不返回它匹配的值

java - 如何使用正则表达式来匹配文本中所有满足的字符串?