Java Replace Special Characters

Posted on 2012-08-14
Last Modified: 2012-08-15
I need to remove this in a Java string:

<?xml version="1.0" encoding="UTF-8"?>

I'm receiving badly formatted xml on a queue that has this tag embedded in the middle of the xml, because of some kind of concatenation on the sender's side.

I've tried:

String toReplace = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
String newString = oldString.replaceAll(toReplace, "");

Does anyone know how to handle this?
Question by:jkavx
    LVL 74

    Accepted Solution

    The replaceAll method takes in a regular expression defining the pattern of text to find. Your problem is that you are using characters which are special to regex and need to be escaped. Try:

    String toReplace = "<\\?xml version=\"1\\.0\" encoding=\"UTF-8\"\\?>";
    String newString = oldString.replaceAll(toReplace, "");

    Open in new window, java.lang.String)
    LVL 86

    Assisted Solution

    If you're not going to take advantage of the regex (say to allow for variations in whitespace, quoting etc.) then it will be easier to do

    String newString = oldString.replace(toReplace, "");

    Open in new window

    LVL 86

    Expert Comment

    The version i posted is also more efficient than using a regex

    Featured Post

    Live: Real-Time Solutions, Start Here

    Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

    Join & Write a Comment

    For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
    Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
    Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
    Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now