Search code examples
javaregexstringnullreplaceall

Erasing String that contains null


I have a null value in my message or println that i want to delete, all succeed when i just using code like this.

the message before :

message = 2014-06-02 14:53:37.103 null tes

Here is the code that delete the null word.

public static void main(String[] args) {
    //final int month = Integer.parseInt(period[0]),  year = Integer.parseInt(period[1]);
    Date x = new Date();
    Timestamp t = new Timestamp(x.getTime());
    String a = "null";
    String b = t+" " +a + " tes";

    String tes = (b.trim()!= null && b.trim().length()>=23) ? b.trim().replaceFirst(b.trim().substring(0,28), ""+t) : b;

    System.out.println("message = " + tes);

}

The printout is right. its like this :

message = 2014-06-02 14:53:37.103 tes

But when i insert this | the printout gone wrong. i'm using that as a separator. This is the code that went wrong.

public static void main(String[] args) {
    //final int month = Integer.parseInt(period[0]),  year = Integer.parseInt(period[1]);
    Date x = new Date();
    Timestamp t = new Timestamp(x.getTime());
    String a = "null";
    String b = t+"| " +a + " tes";

    String tes = (b.trim()!= null && b.trim().length()>=23) ? b.trim().replaceFirst(b.trim().substring(0,28), ""+t) : b;

    System.out.println("message = " + tes);

}

And this is the print out :

message = 2014-06-02 14:58:03.148| null tes

What happen to the second code actually? Thanks


Solution

  • If you want to simply strip out the 'null' text string without the regEx issues above, and quickly and cleanly, just replace the 'null' String directly.

    b.replace("null", "")