![](/img/trans.png)
[英]Java regex: Replace all characters with `+` except instances of a given string
[英]Java RegEx replace all characters in string except for a word
我正在使用Java中的代码:
String word = "hithere";
String str = "123hithere12345hi";
output(str.replaceAll("(?!"+word+")", "x"));
但是,不是像我希望的那样输出: xxxhitherexxxxxxx
,而是输出: x1x2x3hxixtxhxexrxex1x2x3x4x5xhxix x
,我尝试了许多不同的regex模式来尝试执行此操作,但是我似乎不知道如何执行此操作:(
任何帮助将非常感激。
那么这在技术上是可行的。 仅使用替换全部和仅一行,并且假设您的字符串不包含不推荐使用的ASCII字符(BEL)
String string = "hithere";
String string2 = "asdfasdfasdfasdfhithereasasdf";
System.out.println(string2.replaceAll(string,"" + (char)string.length()).replaceAll("[^" + (char)string.length() + "]", "x").replaceAll("" + (char)string.length(), string));
如果我没记错的话,我认为这就是您要寻找的东西:
String pattern = "(\\d)|(hi$)";
System.out.println("123hithere12345hi".replaceAll(pattern, "X"));
该模式将替换所有数字和单词“ hi”。
此基于环境的代码将为您工作:
String word = "hithere";
String string = "123hithere12345hi";
System.out.println(string.replaceAll(
".(?=.*?\\Q" + word + "\\E)|(?<=\\Q" + word + "\\E(.){0,99}).", "x"));
//=> xxxhitherexxxxxxx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.