Reputation: 6960
I have question about regexp in TCL.
How i can find and change some text
in TCL string variable with regexp function.
Example of the text:
/folder/folder2/test-c+a+t -test1 -test2
I want to receive:
/folder/folder2/test-d+o+g
Or for example it can be just:
test-c+a+t
and i want to recieve:
test-d+o+g
Sorry for this addition:
In this situation:
/test-c+a+t/folder2/test-c+a+t -test1 -test2
i want to recieve:
/test-c+a+t/folder2/test-d+o+g -test1 -test2
Upvotes: 0
Views: 337
Reputation: 137567
Either use string map
or use regsub
(possibly with the -all
flag). Here are some examples of the two approaches:
set myString [string map [list "test-c+a+t" "test-d+o+g"] $myString]
set myString [regsub -all "***=test-c+a+t" $myString "test-d+o+g"]
### Or equivalently, for older Tcl versions...
regsub -all "***=test-c+a+t" $myString "test-d+o+g" myString
The string map
can apply multiple changes in one sweep (the mapping a b b a
would swap all a
and b
characters) but it only ever replaces literal strings and always replaces everything it can. The regsub
command can do much more complex transformations and can much more selective about what it replaces, but it does require you to use regular expressions and it is slower in the case where a string map
can do an equivalent job. However, the special leading ***=
in the pattern means that the rest of the pattern is a literal string.
Upvotes: 0
Reputation: 33193
In the specific case you mention here you would do better to use string map. Regular expressions are more flexible though so it all depends how specific your task is.
set modified [string map {test-c+a+t test-d+o+g} $original]
Otherwise, there is no substitute for learning how to use regular expression syntax. It is useful pretty much all the time so read the manual page, try various expressions and re-read the manual when you fail to match what you expected. Also try out sed, awk and grep for learning to use regexp's.
Upvotes: 3
Reputation: 246764
% set old {/folder/folder2/test-c+a+t -test1 -test2}
/folder/folder2/test-c+a+t -test1 -test2
% set new [regsub {(test)-c\+a\+t.*} $old {\1-d+o+g}]
/folder/folder2/test-d+o+g
Note the literal +
symbols need to be escaped because they are regular expression quantifiers.
http://tcl.tk/man/tcl8.5/TclCmd/re_syntax.htm
http://tcl.tk/man/tcl8.5/TclCmd/regsub.htm
Upvotes: 3