Tuesday 11 September 2018

Remove special characters - Groovy Script -SAP HCI/CPI

We had a requirement to remove the special characters in the field in mapping and also remove the prefix "0".

After this if the value starts with 63 or 61 then + should be added at prefix and send to target field

Note: You can find the usage for if condition, replaceAll, startsWith, replaceFirst function, concat, Boolean function

Input: 

"000ew63f@gAH-Je5^%7r/df&6!)78g"

Output:

6357678


Code:


import com.sap.it.api.mapping.*;
def String customFunc(String arg1){
def str5 = ''
def str4 = '+'
// Remove the special characters
       def str2 = arg1.replaceAll("[\\*\\?/()\\-\\^!@_+%.&#a-zA-Z]","")
// remove the leading zero's
def str3 = str2.replaceFirst ("^0*", "")
//condition to check the 63 or 61
if (str3.startsWith("63") || str3.startsWith("61"))
{
  
   str5 = str4.concat(str3)
}

return str5

}

or 

import com.sap.it.api.mapping.*;
def String customFunc(String arg1, String arg2, String arg3){
def len1
def len2
len1 = arg1.length()
len2 = arg2.length()
if( len1 > 0 )
{
def str2 = arg1.replaceAll("[\\*\\?/()\\-\\^!@_+%.&#a-zA-Z]","")
def str3 = str2.replaceFirst ("^0*", "")
def str5
def str6
def str7
if (str3.startsWith("63") || str3.startsWith("61"))
{
    def str4 = "+"
    str5 = str4.concat(str3)
return str5  
}
else 
{
    if( (len2 == 0) && (arg3 == "Melbourne" || arg3 == "Sydney"  )){
  str6 = "+61"
  str7 = str6.concat(str3)
  return str7
    }
}
}
else
{
                return arg1
}
}