[英]Java RegEx replace all characters in string except for a word
I am using the code in Java: 我正在使用Java中的代码:
String word = "hithere";
String str = "123hithere12345hi";
output(str.replaceAll("(?!"+word+")", "x"));
However, rather than outputting: xxxhitherexxxxxxx
like I want it to, it outputs: x1x2x3hxixtxhxexrxex1x2x3x4x5xhxix x
, I've tried a load of different regex patterns to try to do this, but I can't seem to figure out how to do this :( 但是,不是像我希望的那样输出:
xxxhitherexxxxxxx
,而是输出: x1x2x3hxixtxhxexrxex1x2x3x4x5xhxix x
,我尝试了许多不同的regex模式来尝试执行此操作,但是我似乎不知道如何执行此操作:(
Any help would be much appreciated. 任何帮助将非常感激。
Well this technically works. 那么这在技术上是可行的。 Using only replace all and only one line, and it's assuming you string does not contain a deprecated ASCII character (BEL)
仅使用替换全部和仅一行,并且假设您的字符串不包含不推荐使用的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));
I think this is what you're looking for, if I'm not mistaken: 如果我没记错的话,我认为这就是您要寻找的东西:
String pattern = "(\\d)|(hi$)";
System.out.println("123hithere12345hi".replaceAll(pattern, "X"));
The pattern replaces any numeric digits and the word "hi". 该模式将替换所有数字和单词“ hi”。
This lookaround based code will work for you: 此基于环境的代码将为您工作:
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.