0

I have to replace a string whit special character like this: XY_Universit�-WWWWW-ZZZZZ in another one like: XY_Universita-WWWWW-ZZZZZ.

I tried solutions like stringToReplace.replaceAll(".*Universit.*", "Universita"); but it replace all the string with the word ''Universita" and it isn't what i want.

user11153
  • 8,536
  • 5
  • 47
  • 50
Zany
  • 308
  • 1
  • 4
  • 18
  • Is that special character the only way Universit can end with, or do also have different uses? That is, do we have to confirm it's that character? – Deltharis Oct 13 '14 at 08:37
  • 1
    possible duplicate of [replace special characters in string in java](http://stackoverflow.com/questions/2608205/replace-special-characters-in-string-in-java) – ethanfar Oct 13 '14 at 10:24
  • How did you get the �? Maybe you should go back a few steps and get the real character. – Tom Blodget Oct 13 '14 at 22:49
  • i'm reading from file. The word is 'Università'. – Zany Oct 14 '14 at 08:19
  • To read a file, you must know the character set and encoding used. Usually, you would just know that it is the "platform default" and that programs adapt to that, whatever it is. If you get a file from another person or system, you have to have an agreement or specification. Then, you can use code like this `java.nio.file.Files.readAllLines(java.nio.file.Paths.get("file.txt"), java.nio.charset.Charset.forName("Windows-1252"))`. Substitute in whatever encoding you know the file to be using. – Tom Blodget Oct 14 '14 at 23:52

4 Answers4

1

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

hsluo
  • 1,652
  • 15
  • 20
1
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
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
1

You have to be lazy :P

use : .*?XY_Universit. to select only the first XY_universit

demo here

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

Another odd way..

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