I need to trim a string , say abc+cd+ze:::123:::12+abcd , given 123 , I need to extract ze:::123:::12.
As Screwtape said it's quite easy to do this using ENTRY
.
If you for some reason want to use the INDEX
and search positions you can do like this. R-INDEX
will help you - searching the string from right to left instead of left to right.
This example will have issues if you for instance have multiple entries that match your searching string. In that case it will return the leftmost matching entry.
DEFINE VARIABLE cString AS CHARACTER NO-UNDO.
DEFINE VARIABLE cSearch AS CHARACTER NO-UNDO.
DEFINE VARIABLE cResult AS CHARACTER NO-UNDO.
DEFINE VARIABLE iPosition AS INTEGER NO-UNDO.
DEFINE VARIABLE iLeftPlus AS INTEGER NO-UNDO.
DEFINE VARIABLE iRightPlus AS INTEGER NO-UNDO.
DEFINE VARIABLE iLength AS INTEGER NO-UNDO.
/* This is the string we're searching in */
cString = "abc+cd+ze:::123:::12+abcd".
/* This is what we're searching for */
cSearch = "123".
/* Get a starting position */
iPosition = INDEX(cString, cSearch).
/* Start at starting position and look right-to-left for a plus sign */
/* Add 1 since we don't want the plus sign */
iLeftPlus = R-INDEX(cString, "+", iPosition) + 1.
/* Start at starting position and look left-to-right for a plus sign */
iRightPlus = INDEX(cString, "+", iPosition).
/* If there isn't a rightmost + */
IF iRightPlus = 0 THEN
iRightPlus = LENGTH(cString).
/* Calculate the length of the result string */
iLength = iRightPlus - iLeftPlus.
/* Use substring to create resulting string */
cResult = SUBSTRING(cString, iLeftPlus, iLength).
MESSAGE cResult VIEW-AS ALERT-BOX INFORMATION.