Talend Equivalent for TRIM Function in Datastage

 
package routines;

public class UserString {

    /**
     * 
     * L Removes leading occurrences of character.
     * T Removes trailing occurrences of character.
     * B Removes leading and trailing occurrences of character.
     * R Removes leading and trailing occurrences of character, and reduces multiple occurrences to a single occurrence.
     * A Removes all occurrences of character.
     * F Removes leading spaces and tabs
     * E Removes trailing spaces and tabs
     * D Removes leading and trailing spaces and tabs, and reduces multiple spaces and tabs to single ones.
     */
    public static String TRIM(String str, String character, String option) {
    	String returnStr = "";
    	if (str == null) {
    		return null;
    	}
    	if (option.equals("L")) {
    		returnStr = str.replaceFirst("^" + character + "+", "");
    	} else if (option.equals("T")) {
    		returnStr = str.replaceAll("[" + character + "]+$", "");
    	} else if (option.equals("B")) {
    		returnStr = str.replaceFirst("^" + character + "+", "");
    		returnStr = returnStr.replaceAll("[" + character + "]+$", "");
    	} else if (option.equals("R")) {
    		returnStr = str.replaceFirst("^" + character + "+", "");
    		returnStr = returnStr.replaceAll("[" + character + "]+$", "");
    		returnStr = avoidMultipleOccurrence(returnStr, character);
    	} else if (option.equals("A")) {
    		returnStr = str.replaceAll(character, "");	
    	} else if (option.equals("F")) {
    		returnStr = TRIM(str, " ", "L");
    		returnStr = TRIM(returnStr, "\t", "L");
    	} else if (option.equals("E")) {
    		returnStr = TRIM(str, " ", "T");
    		returnStr = TRIM(returnStr, "\t", "T");
    	} else if (option.equals("D")) {
    		returnStr = TRIM(str, "", "F");
    		returnStr = TRIM(returnStr, "", "E");
    		returnStr = avoidMultipleOccurrence(returnStr, " ");
    		returnStr = avoidMultipleOccurrence(returnStr, "\t");
    	} 
    	return returnStr;
    }
    
    public static String TRIM(String str) {
    	return (str == null) ? null : TRIM(str, " ", "R");
    }
    
    public static String avoidMultipleOccurrence(String input, String character) {    	
    	if (input == null) {
    		return null;
    	}
    	if (input.length() == 0) {
    		return input;
    	}
    	StringBuilder output = new StringBuilder();
    	output.append(input.charAt(0));    	 
    	for (int idx = 1; idx < input.length(); idx++) {
    		if (Character.toString(input.charAt(idx)).equals(character)) {
	    	    if(input.charAt(idx) != input.charAt(idx-1)) {
	    	        output.append(input.charAt(idx));
	    	    }
    	    } else {
    	    	output.append(input.charAt(idx));
    	    }
    	}
    	return output.toString();
    }
}

Post a Comment

0 Comments