Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get multiple matches with tcl regexp

How do I get all the matches in tcl using regexp command? For example I have a string as following

set line "foo \"aaa\"zz bar \"aaa:ccc\" ccc"
puts $line
foo "aaa"zz bar "aaa:ccc" ccc

I now want to get aaa and aaa:ccc. There could be any number of such matches.
I tried

regexp -all -inline {"(.*)"} $line 
{"aaa"zz bar "aaa:ccc"} {aaa"zz bar "aaa:ccc}

But as seen this didn’t work. What’s the right way to get multiple matches and match everything within double quotes?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can capture all between two quotes with "([^"]*)" pattern. When using the pattern with regexp -all -inline:

set matches [regexp -all -inline {"([^"]*)"} $line]

you will get all overall match values and all the captured substrings.

You will have to post-process the matches in order to get the final list of captures:

set line "foo \"aaa\"zz bar \"aaa:ccc\" ccc"
set matches [regexp -all -inline {"([^"]*)"} $line]
set res {}
foreach {match capture} $matches {
    lappend res $capture
}
puts $res

See the online Tcl demo.

Output:

aaa aaa:ccc
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading