如何从最近的最近+和最近的最近+修剪一个字符串?正在进行4gl

时间:2016-03-24 08:42:00

标签: string trim progress-4gl openedge 4gl

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

2 个答案:

答案 0 :(得分:1)

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

这似乎对我有用:

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.

答案 1 :(得分:0)

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

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

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

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.