How to get text within quotes and store in a list using tcl commands

I would like to get text within quotes into a list. It might be single or double qoutes.

ex_string :

( "abc_|a'b" | 'bda' | "bb-  'ds" | 'aac'(!)     = '--  ok' : text= 'abc')

And i want the list to be like

{abc_|a'b} {bda} {bb-  'ds} {aac} {-- ok} {abc}

Upvotes: 0

Views: 289

Answers (3)

Schelte Bron
Schelte Bron

Reputation: 4813

Similar to Donal Fellows' answer, but using a non-greedy regular expression:

set str {( "abc_|a'b" | 'bda' | "bb-  'ds" | 'aac'(!)     = '--  ok' : text= 'abc')}
set items [lmap {- - s} [regexp -all -inline {(['"])(.*?)\1} $str] {set s}]
puts "found: $items"
# found: abc_|a'b bda {bb-  'ds} aac {--  ok} abc

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137567

This is the sort of thing that a regular expression can solve. However, you've got to post-process the results (lmap and string cat are perfect for the task in this case):

set str {( "abc_|a'b" | 'bda' | "bb-  'ds" | 'aac'(!)     = '--  ok' : text= 'abc')}
set items [lmap {a b c} [regexp -all -inline {"([^\"]*)"|'([^\']*)'} $str] {
    string cat $b $c
}]
puts "found: $items"
# found: abc_|a'b bda {bb-  'ds} aac {--  ok} abc

There's no braces around items that don't need it. I'd expect you to be OK with that usually…

Upvotes: 2

Peter Lewerin
Peter Lewerin

Reputation: 13252

You could do it like this:

% set a {( "abc_|a'b" | 'bda' | "bb-'ds" | 'aac'(!) = '--ok')}
( "abc_|a'b" | 'bda' | "bb-'ds" | 'aac'(!) = '--ok')
% set b [string trim $a {() }]
"abc_|a'b" | 'bda' | "bb-'ds" | 'aac'(!) = '--ok'
% set c [string map {{ | } { } { = } { } {(!)} {}} $b]
"abc_|a'b" 'bda' "bb-'ds" 'aac' '--ok'
% concat {*}[lmap item $c {format "{%s}" [string trim $item {"'}]}]
{abc_|a'b} {bda} {bb-'ds} {aac} {--ok}

I'll explain later if necessary.

Documentation: concat, format, lmap (for Tcl 8.5), lmap, set, string, {*} (syntax)

Upvotes: 1

Related Questions