[英]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.