gpt4 book ai didi

Java 用正则表达式替换全部

转载 作者:太空宇宙 更新时间:2023-11-04 06:07:48 26 4
gpt4 key购买 nike

我收到了用户的输入:

*.*.*.*

(* = 审查)该字符串是用户的输入,这就是用户想要审查的内容。如何将其转换为正则表达式?编辑:让我再解释一下。用户想要审查 * 中点之间的任何内容,因此他输入 *.*.*.*,我需要将其转换为正则表达式。他也可以输入文本*文本

我尝试过这样做:

String strLine = "93.38.31.43 and 39.53.19.33 and lala.lala.lala.lala";
String input = "*.*.*.*";
String replaceWord = "[censor]";
input = input.replaceAll("\\*","\\\\\\w+");
strLine = strLine.replaceAll("(?=\\s+)\\S*)" + input + "(?=\\s+)\\S*",replaceWord);

我尝试用\\w+ 替换 * 以获得此输出:

the ip's are [censor] and [censor] and [censor]

但它不起作用,也不能取代任何东西。

当我这样做时,它有效:

strLine = strLine.replaceAll("?<=\\s+)\\S*" +"\\w+\\.\\w+\\.\\w+\\.\\w+"+"(?\\s+)\\S*",replaceWord);

为什么不起作用?有更好的方法吗?

最佳答案

您可以使用:

String strLine = "93.38.31.43 and 39.53.19.33 and lala.lala.lala.lala";
String input = "*.*.*.*";
String replaceWord = "[censor]";

input = input.replace("*","\\w+").replace(".", "\\.");
System.out.println(input); // \w+\.\w+\.\w+\.\w+

strLine = strLine.replaceAll("\\b" + input + "\\b", replaceWord);
System.out.println(strLine);
//=> [censor] and [censor] and [censor]

关于Java 用正则表达式替换全部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29093432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com