In SAP Cloud Platform Integration (CPI), substring operations are commonly used to extract specific parts of a string, such as pulling out IDs, dates, or codes from larger text values. Groovy scripting makes this easy and flexible during message mapping or script steps.
When to Use Substring in SAP CPI
Use substring logic when you need to
- Extract part of a customer or product ID.
- Derive company or plant codes from a longer text.
- Split a date or reference number.
- Remove prefixes or suffixes from fields.
Also Read: Groovy Script in SAP CPI Message Mapping – Complete Guide for Beginners
Example 1: Simple Substring Extraction
Suppose your input is “CUST_12345”, and you only need the numeric portion after the underscore.
def String extractSubstring(String input) {
if (input == null || !input.contains("_")) {
return input
}
def index = input.indexOf("_") + 1
return input.substring(index)
}
Input: CUST_12345
Output: 12345
Here, indexOf("_") locates the underscore, and substring(index + 1) extracts the part after it.
If you only need fixed positions, you can use
input.substring(0, 4) // first 4 characters
input.substring(2, 6) // characters from index 2 to 5
Example 2: Substring Inside a Script Step
You can also use substring directly in a Groovy Script step inside your integration flow.
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
def body = message.getBody(String)
def result = body.substring(0, 5)
message.setBody(result)
return message
}
If your input message body is "ABCDEFGHIJ", the output will be "ABCDE".
Also Read: SAP Datasphere Connection to SAP ECC – Step-by-Step Integration Guide
Example 3: Substring from Message Header or Property
When you need to extract parts of header or property values, you can use
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
def headerValue = message.getHeader("CustomerID")
def shortID = headerValue.substring(2, 6)
message.setProperty("ShortID", shortID)
return message
}
This stores the shortened ID in a message property for reuse later in the flow.
Best Practices
- Always validate input before using
substring()to prevent null or range errors. - Remember that Groovy uses zero-based indexing.
- For variable-length inputs, use
input.length()to ensure safety. - Use logging for debugging if you are unsure about index values.
Summary
The substring method in Groovy is a quick way to manipulate strings in SAP CPI. It helps clean and reformat data directly in mappings or script steps without external processing. By combining indexOf() and substring(), you can create precise, dynamic extractions that make your integration logic cleaner and more efficient.