Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Splitting a string based on a pattern of chars, not a single char

Status
Not open for further replies.

LilTCLer

Programmer
Nov 27, 2007
37
US
Is there a way to use the split function to split data based on a pattern of chars instead of a single char?

For example, I have exported data from a query and wish to split this data at the words (pattern) "RZDoorsRequirement"

I try: set splitData [ split $data "RZDoorsRequirement" ], but this doesn't work correctly where the data is as follows:

Data equals (as read into TCL buffer from file:
RZDoorsRequirement|G709 Requirements|634|I-Req|The Line Interface shall transmit at a nominal power level of 5.0dBm.|
RZDoorsRequirement|G709 Requirements|635|I-Req|The Line Interface shall support line side reception in the range of +1dBm to -26dBM.|
RZDoorsRequirement|G709 Requirements|793|I-Req|The Line Interface shall support 100km chromatic dispersion toloerance.|

Is there any way to do this?
 
Unfortunately split recognizes your pattern as a set of individual delimiting characters, so I think you need to have 2 steps.
1 - use string map to change your delimiter, "RZDoorsRequirement", to a useful character, say a linefeed (\n):
set lfData [string map {RZDoorsRequirement "\n"} $data]
2 - split on that delimiter:
set splitData [split $lfData \n]

_________________
Bob Rashkin
 
Well thats essentially what I had to do, but I didn't want to do it that way. Instead of the "string map", I used:

regsub -all "RZDoorsRequirement" $data "@" data

The purpose of my script was to re-format the data by removing extraneous "\n" 's so that MS Excel could "nicely" display the delimited text. By changing the string "RZDoorsRequirement" to "@", I was able to use the "split" function by delimiting at the "@". Luckily, there wasn't any other "@" chars in the data, otherwise, it wouldn't have split correctly. I'm surprised that there isn't a way to split based on a pattern string.
 
It's spretty simple to cook one up.
Code:
proc msplit {pattern str} {
                 set t [expr [string length $pattern] - 1]
                   for {set i 0} {$i < [string length $str]} {incr i $t} {
                       if {[string compare $pattern [string range $str $i [expr $i + $t]]] == 0} {
                       return [string range $str [expr $i + $t] [string length $str]]
                        }
                     #puts "Compared $pattern [string range $str $i [expr $i + $t]]"
                       
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top