loveclassic
loveclassic

Reputation: 25

Split a string using TCL

I'm a newbie to TCL and I'm trying to split the string below into a list:

Sep 20, 07:45:12, 100.1.1.1

My expectation is:

{Sep 20} {07:45:12} {100.1.1.1}

Could anyone help me with a simple solution ? I have my own way but it's a little bit complex Thanks

Upvotes: 1

Views: 2328

Answers (3)

Peter Lewerin
Peter Lewerin

Reputation: 13252

For completeness; requires Tcl 8.6+ (8.5 with the pure-Tcl add-on mentioned below):

set txt "Sep 20, 07:45:12, 100.1.1.1"
lmap item [split $txt ,] {string trim $item}
# => {Sep 20} 07:45:12 100.1.1.1

Documentation: lmap (for Tcl 8.5), lmap, set, split, string

Upvotes: 0

Sharad
Sharad

Reputation: 10602

% set foo "Sep 20, 07:45:12, 100.1.1.1"
Sep 20, 07:45:12, 100.1.1.1
% split [regsub -all {,\s+} $foo ,] ,    
{Sep 20} 07:45:12 100.1.1.1
% 

Enclose any of the items with curly braces as needed, explicitly. From TCL's perspective, it just a mechanism to show a space separated string. For e.g.,

% split "foo bar, bar bat, bat foo" ,
{foo bar} { bar bat} { bat foo}
% 

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137567

Since you're using a multicharacter separator sequence, it's easiest to use string map to convert it into a single rare character (something in the “unusual” part of Unicode will do; we'll use the escaped version of that) and then split on that. It's really a one-liner…

set theString "Sep 20, 07:45:12, 100.1.1.1"
set pieces [split [string map {", " \uffff} $theString] \uffff]

You can also use the splitx stuff in Tcllib for this, but it's overkill for this case.

Upvotes: 1

Related Questions