]> www.wagner.pp.ru Git - sites/home_page.git/blob - software/tcl/xsplit.html
Reentered after crash of all CVS repositories
[sites/home_page.git] / software / tcl / xsplit.html
1 <HTML><HEAD>
2 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=koi8-r">
3 <TITLE>Extended Split command for Tcl</TITLE>
4 <META NAME="description" CONTENT="Split the string on arbitrary regular expression">
5 </HEAD><BODY>
6 <H1>Extended split command</H1>
7
8 Being forced to use perl instead of Tcl, I've noticed that Perl
9 <B>split</B> command is much more powerful than Tcl one - it allows
10 to split strings on arbitrary regexps rather than on particular char,
11 and, optionally, allows to put element separators in the resulting list
12 as separate elements.
13 <P>
14 Fortunately, <B>regexp</B> command in Tcl is powerful enough to
15 implement Perl-like split just in few lines of Tcl code.
16 <P>
17 Behold:
18 <PRE>
19 proc xsplit [list str [list regexp &quot;\[\t \r\n\]+&quot;]] {
20     set list  {}
21     while {[regexp -indices -- $regexp $str match submatch]} {
22         lappend list [string range $str 0 [expr [lindex $match 0] -1]]
23         if {[lindex $submatch 0]&gt;=0} {
24             lappend list [string range $str [lindex $submatch 0]\
25                     [lindex $submatch 1]] 
26         }       
27         set str [string range $str [expr [lindex $match 1]+1] end] 
28     }
29     lappend list $str
30     return $list
31 }
32 </PRE>
33 <p>
34 This command behaves much like Tcl built-in <B>split</B>, but it
35 takes regexp as second argument, and defaults it to arbitrary amount
36 of whitespace. If regexp contains parentesis, text, which matches them
37 would be inserted in resulting list between splitted items as separate
38 elements.
39 </P>
40 </BODY>
41 </HTML>