简体   繁体   English

替换字符串中的特殊字符

[英]Replace special character in a String

I have to replace a string whit special character like this: XY_Universit -WWWWW-ZZZZZ in another one like: XY_Universita-WWWWW-ZZZZZ . 我必须替换一个像这样的特殊字符字符串: XY_Universit -WWWWW-ZZZZZ ,另一个XY_Universita-WWWWW-ZZZZZXY_Universita-WWWWW-ZZZZZ

I tried solutions like stringToReplace.replaceAll(".*Universit.*", "Universita"); 我尝试过像stringToReplace.replaceAll(".*Universit.*", "Universita");这样的解决方案stringToReplace.replaceAll(".*Universit.*", "Universita"); but it replace all the string with the word ''Universita" and it isn't what i want. 但是它将所有字符串替换为“ Universita”一词,这不是我想要的。

stringToReplace.replaceAll("Universit[^a]", "Universita")

public static void main(String[] args) throws IOException {
        String exp = "XY_Universit�-WWWWW-ZZZZZ";
        exp = exp.replaceAll("[^\\w\\s\\-_]", "");
        System.out.println(exp);
    }

output 产量

XY_Universit-WWWWW-ZZZZZ

You have to be lazy :P 你必须懒惰 :P

use : .*?XY_Universit. 使用: .*?XY_Universit. to select only the first XY_universit 只选择第一个XY_universit

demo here 在这里演示

Another odd way.. 另一个奇怪的方法

String example = "XY_Universit�-WWWWW-ZZZZZ";
char ch = 65533; //find ascii of special char
System.out.println(example.replace(ch, 'a'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM