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.

5
  • 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? Commented Oct 13, 2014 at 8:37
  • 1
    possible duplicate of replace special characters in string in java Commented Oct 13, 2014 at 10:24
  • How did you get the �? Maybe you should go back a few steps and get the real character. Commented Oct 13, 2014 at 22:49
  • i'm reading from file. The word is 'Università'. Commented Oct 14, 2014 at 8: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. Commented Oct 14, 2014 at 23:52

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

You have to be lazy :P

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

demo here

Comments

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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.