factor/basis/regexp/matchers/matchers.factor

60 lines
1.6 KiB
Factor
Raw Normal View History

2009-02-26 19:06:57 -05:00
! Copyright (C) 2008, 2009 Daniel Ehrenberg, Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
2009-02-26 23:14:41 -05:00
USING: kernel sequences math splitting make fry locals math.ranges
accessors arrays ;
2009-02-26 19:06:57 -05:00
IN: regexp.matchers
! For now, a matcher is just something with a method to do the
! equivalent of match.
2009-02-26 23:14:41 -05:00
GENERIC: match-index-from ( i string matcher -- index/f )
2009-02-26 19:06:57 -05:00
2009-02-26 23:14:41 -05:00
: match-index-head ( string matcher -- index/f )
[ 0 ] 2dip match-index-from ;
: match-slice ( i string matcher -- slice/f )
[ 2dup ] dip match-index-from
[ swap <slice> ] [ 2drop f ] if* ;
2009-02-26 19:06:57 -05:00
: matches? ( string matcher -- ? )
2009-02-26 23:14:41 -05:00
dupd match-index-head
2009-02-26 19:06:57 -05:00
[ swap length = ] [ drop f ] if* ;
2009-02-26 23:14:41 -05:00
:: match-from ( i string matcher -- slice/f )
i string length [a,b)
[ string matcher match-slice ] map-find drop ;
2009-02-26 19:06:57 -05:00
2009-02-26 23:14:41 -05:00
: match-head ( str matcher -- slice/f )
[ 0 ] 2dip match-from ;
2009-02-26 19:06:57 -05:00
<PRIVATE
2009-02-26 23:14:41 -05:00
: next-match ( i string matcher -- i match/f )
match-from [ dup [ to>> ] when ] keep ;
2009-02-26 19:06:57 -05:00
PRIVATE>
2009-02-26 23:14:41 -05:00
:: all-matches ( string matcher -- seq )
2009-03-03 13:41:50 -05:00
0 [ dup ] [ string matcher next-match ] produce nip but-last ;
2009-02-26 23:14:41 -05:00
: count-matches ( string matcher -- n )
all-matches length ;
2009-02-26 19:06:57 -05:00
<PRIVATE
2009-02-26 23:14:41 -05:00
:: split-slices ( string slices -- new-slices )
slices [ to>> ] map 0 prefix
slices [ from>> ] map string length suffix
[ string <slice> ] 2map ;
2009-02-26 19:06:57 -05:00
PRIVATE>
2009-02-26 23:14:41 -05:00
: re-split1 ( string matcher -- before after/f )
dupd match-head [ 1array split-slices first2 ] [ f ] if* ;
2009-02-26 19:06:57 -05:00
: re-split ( string matcher -- seq )
2009-02-26 23:14:41 -05:00
dupd all-matches split-slices ;
2009-02-26 19:06:57 -05:00
: re-replace ( string matcher replacement -- result )
[ re-split ] dip join ;