如何 trim 从最左边最近的 + 到最右边最近的 + 的字符串?进行中 4gl

How to trim a string from leftmost nearest + and rightmost nearest +? in progress 4gl

我需要 trim 一个字符串,比如 abc+cd+ze:::123:::12+abcd,给定 123,我需要提取 ze:::123:::12。

虽然从表面上看,substring 是显而易见的方式,因为您正在寻找两个分隔符之间的东西,实际上 ENTRY 更容易。但是,这只有在您可以保证要查找的字符串不包含分隔符时才有效。 Progress 无法解码引用的或以其他方式转义的定界符。

这似乎对我有用:

DEF VAR testStr AS CHAR INITIAL "abc+cd+ze:::123:::12+abcd".
DEF VAR matchStr AS CHAR INITIAL "123".
DEF VAR outStr AS CHAR.
DEF VAR delim AS CHAR INITIAL "+".

DEF VAR i AS INT.

DO i = 1 TO NUM-ENTRIES( testStr, delim ): 
  IF ENTRY( i, testStr, delim ) MATCHES "*" + matchStr + "*" THEN DO:
    outStr = ENTRY( i, testStr, delim ).
    LEAVE.
  END.
END.

DISPLAY outStr.

正如 Screwtape 所说,使用 ENTRY 很容易做到这一点。

如果您出于某种原因想要使用 INDEX 和搜索位置,您可以这样做。 R-INDEX 将帮助您 - 从右到左而不是从左到右搜索字符串。

例如,如果您有多个条目与您的搜索字符串匹配,则此示例会出现问题。在这种情况下,它将 return 最左边的匹配条目。

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.