简体   繁体   中英

TCL split text string to multiple variables (eggdrop)

I am working on a mysql select and insert script but i am having issues with extracting a single line into two variables.

The line is handed as variable $arg and is composed by: "text field 1=text field 2" i try to split $arg by regexp using "=" as the seperator into $arg1 and $arg2 but i always and up with the whole line being parsed to $arg2 and $arg1 being empty.

regexp -- {(\S+)=(\S+)} $arg null $arg1 $arg2

i have tried several methods with regexp and changing the separator but the result remains the same. It is being done with tcl v8.5.

I am not very familiar with tcl so i suspect it's mainly due to lag of understanding of tcl/tk.

Use the name of the variable, not the variable value itself:

regexp -- {(\S+)=(\S+)} $arg null arg1 arg2

If you use $var1 it will be replaced with the value of that variable before the command is invoked, at which point the command doesn't have any idea about what variable has been used.

You could use split as an alternative too:

% set results [split $arg "="]

Which gives you a list containing the two parts you're looking for.

And you can then use lindex to refer to each element.

% puts [lindex $results 0]
text field 1
% puts [lindex $results 1]
text field 2

Or if you want to store them in variables arg1 and arg2 , you could use lassign :

% lassign $results arg1 arg2
% puts $arg1
text field 1
% puts $arg2
text field 2

When parsing these sorts of things, you should take care to only match exactly what you expect. (You need to remember that whenever you are assigning to a variable with Tcl, you need to give the name of the variable — arg1 — as opposed to the contents of the variable — $arg1 .)

regexp -- {([^\s=])=(\S+)} $arg null arg1 arg2

You should also check the result of that regexp call, to see if the RE matched or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM