KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Parsing encapsulated strings
PRODUCT: 4D | VERSION: 2003 | PLATFORM: Mac & Win
Published On: April 1, 2004

When you are parsing through text, it might be useful to isolate encapsulations of strings. For example, everything appearing between an opening bracket ([) and a closing bracket (]). But what happens if you have nested brackets? This method will grab everything between a set of brackets even if they have nested brackets.

  ` it produces well-formed encapsulations at the outermost level
  ` it also assumes that the opening tag is different from the closing tag
C_TEXT($1;$2;$3;$0)
C_TEXT($open;$close;$in;$out;$parse;$char)
C_LONGINT($depth;$cursor)

$in:=$1
$open:=$2
$close:=$3

If (Position($open;$in)#0)
  ` get the first occurance of the opening encapsulation
  $parse:=Substring($in;Position($open;$in))
  $cursor:=1
  Repeat
    $char:=Substring($parse;$cursor;1)

    Case of
      : ($char=$open)
        $depth:=$depth+1
      : ($char=$close)
        $depth:=$depth-1
    End case

    $out:=$out+$char
    $cursor:=$cursor+1

  Until (($depth=0) | ($cursor>Length($parse)))
  $0:=$out
Else
  $0:=$in
End if

Note: If both your open and close arguments are the same, the method will not be able to distinguish the two apart. When calculating depth, the depth will be incremented but never decremented. The string returned will then be everything to the right of the first occurance of the open tag.