<forth xmlns="http://forth.org.ru/ForthML/">
<!-- $Id: match.f.xml,v 1.10 2009/05/04 14:52:37 ruv Exp $ -->
<!-- some ported from ~pinka/samples/2005/lib/split.f -->

<!-- Functions Based on Substring Matching -->

<!-- string length is calculated in units of address (!) -->

<def name="CONTAINS" ds=" a u a-key u-key -- flag ">
  SEARCH NIP NIP
</def>
<def name="STARTS-WITH" ds=" a u a-key u-key -- flag ">
  ROT OVER ULT <if> 2DROP DROP FALSE <exit/></if>
  TUCK EQUAL
</def>
<def name="ENDS-WITH" ds=" a u a-key u-key -- flag ">
  DUP >R 2SWAP DUP R@ ULT <if> 2DROP 2DROP RDROP FALSE <exit/></if>
  R@ - + R> EQUAL
</def>
<def name="SUBSTRING-AFTER" ds=" a u a-key u-key -- a2 u2 ">
  DUP >R SEARCH <if> SWAP R@ + SWAP R> - <exit/></if> RDROP 2DROP 0 0
</def>
<def name="SUBSTRING-BEFORE" ds=" a u a-key u-key -- a2 u2 ">
  3 PICK >R  SEARCH  <if> DROP R> TUCK - <exit/></if>  RDROP 2DROP 0 0
</def>

<def name="SPLIT-" ds=" a u a-key u-key -- a-right u-right  a-left u-left  true  |  a u false ">
  3 PICK >R DUP >R <!-- ( R: a u1 ) -->
  SEARCH   <if><!-- ( aa uu ) -->
  OVER R@ + SWAP R> - <!-- aa+u1 uu-u1  - right part  -->
  ROT R@ - R> SWAP    <!-- a aa-a       - left part   -->
  TRUE <exit/></if>

  2R> 2DROP FALSE
</def>

<def name="SPLIT" ds=" a u a-key u-key -- a-left u-left  a-right u-right  true  |  a u false ">
  DUP >R 3 PICK >R <!-- ( R: u1 a ) -->
  SEARCH   <if><!-- ( aa uu ) -->
  SWAP R@ OVER R> -     <!-- a aa-a       - left part  -->
  2SWAP R@ + SWAP R> -  <!-- aa+u1 uu-u1  - right part -->
  TRUE <exit/></if>

  2R> 2DROP FALSE
</def>

<def name="MATCH-HEAD" ds=" a u a-key u-key -- a-right u-right true | a u false">
  2 PICK OVER ULT <if> 2DROP FALSE <exit/></if>
  DUP >R
  3 PICK R@ EQUAL <unless> RDROP FALSE <exit/></unless>
  SWAP R@ + SWAP R> - TRUE
</def>

<def name="MATCH-TAIL" ds=" a u a-key u-key -- a-left u-left true | a u false">
  2 PICK OVER ULT <if> 2DROP FALSE <exit/></if>
  DUP >R
  2OVER R@ - + R@ EQUAL <unless> RDROP FALSE <exit/></unless>
  R> - TRUE
</def>

<!-- old name: -->
<def name="MATCH-STARTS"> MATCH-HEAD </def>

</forth>