I was trying replace null , .null or null. string from below code snippet

  static String str1="WTDocument: null ( 0000000043 ) A.1";
     static String str2= "WTPart: null ( WHEEL_A1 ) null.null";
     static String str3= "WTPart: null ( WHEEL_A1 ) A.null";
     static String str4= ":null ( number ) OBJECTnull.null";
     static String str5= ":PRE null POST ( number ) null.null";

 

Tried this function

  public static String replaceFunction(String str){
        str=    str.replaceAll("(.)?null?(.)", "").trim();
            return str;
        }

and got output

   WTDocument:( 0000000043 ) A.1
    WTPart:( WHEEL_A1 )
    WTPart:( WHEEL_A1 ) A
    ( number ) OBJEC
    :PREPOST ( number )

But expecting

str1="WTDocument:  ( 0000000043 ) A.1";
str2= "WTPart:  ( WHEEL_A1 ) ";
str3= "WTPart: ( WHEEL_A1 ) A.";
str4= ": ( number ) OBJECTnull
str5= ":PRE  POST ( number ) ";

How can we achieve this replaceAll?

1

There are 1 best solutions below

2
On

Finally got it working:

   String str1="WTDocument: null ( 0000000043 ) A.1";
   String str2= "WTPart: null ( WHEEL_A1 ) null.null";
   String str3= "WTPart: null ( WHEEL_A1 ) A.null";
   String str4= ":null ( number ) OBJECTnull.null";
   String str5= ":PRE null POST ( number ) null.null";
   System.out.println(str1.replaceAll("\\s*\\bnull?\\b\\.?|\\s*\\.\\bnull?\\b\\.?|(null)\\W*", ""));
   System.out.println(str2.replaceAll("\\s*\\bnull?\\b\\.?|\\s*\\.\\bnull?\\b\\.?|(null)\\W*", ""));
   System.out.println(str3.replaceAll("\\s*\\bnull?\\b\\.?|\\s*\\.\\bnull?\\b\\.?|(null)\\W*", ""));
   System.out.println(str4.replaceAll("\\s*\\bnull?\\b\\.?|\\s*\\.\\bnull?\\b\\.?|(null)\\W*", ""));
   System.out.println(str5.replaceAll("\\s*\\bnull?\\b\\.?|\\s*\\.\\bnull?\\b\\.?|(null)\\W*", ""));

Check the output:

WTDocument: ( 0000000043 ) A.1
WTPart: ( WHEEL_A1 )
WTPart: ( WHEEL_A1 ) A
: ( number ) OBJECT
:PRE POST ( number )


** Process exited - Return Code: 0 **