用Java正则表达式编辑单词
假设我有一个正则表达式字符串用Java正则表达式编辑单词,java,regex,string,Java,Regex,String,假设我有一个正则表达式字符串stringreg 考虑一块文本,字符串文本 我想在text上使用regexreg,对于每个匹配项,用长度为匹配项的*字符串替换匹配项 如何执行此操作?您可以使用重复*字符 演示: import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) { // Test
stringreg
考虑一块文本,字符串文本
我想在text
上使用regexreg
,对于每个匹配项,用长度为匹配项的*
字符串替换匹配项
如何执行此操作?您可以使用重复*
字符
演示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(maskMatch(
"Hello world. Hi there. The word, hello is very common. Abchelloxyz also has hello but it will not be masked as it does not match the regex.",
"\\bhello\\b"));
}
static String maskMatch(String text, String reg) {
StringBuilder sb = new StringBuilder(text);
Matcher matcher = Pattern.compile(reg).matcher(text);
while (matcher.find()) {
sb.replace(matcher.start(), matcher.end(), "*".repeat(matcher.group().length()));
}
return sb.toString();
}
}
Hello world. Hi there. The word, ***** is very common. Abchelloxyz also has ***** but it will not be masked as it does not match the regex.
输出:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(maskMatch(
"Hello world. Hi there. The word, hello is very common. Abchelloxyz also has hello but it will not be masked as it does not match the regex.",
"\\bhello\\b"));
}
static String maskMatch(String text, String reg) {
StringBuilder sb = new StringBuilder(text);
Matcher matcher = Pattern.compile(reg).matcher(text);
while (matcher.find()) {
sb.replace(matcher.start(), matcher.end(), "*".repeat(matcher.group().length()));
}
return sb.toString();
}
}
Hello world. Hi there. The word, ***** is very common. Abchelloxyz also has ***** but it will not be masked as it does not match the regex.
了解有关Java正则表达式API的更多信息,请访问
reg.length()
对于包含除
以外的元字符的任何模式都是不正确的。而且reg
已经是一个正则表达式,因此添加(?i)
或\\b
@VGR可能没有效果-您错了。使用元字符(例如maskMatch(“你好,世界。你好。这个词,他@VGR-啊,自从我最初的评论以来,我不知道你已经更新了你的答案。看起来不错。如果答案不符合你的要求,你应该在它下面评论。如果符合,一条确认相同的评论对未来的访问者(贡献者或学习者)会有帮助。”。