How to use "regsub" or "regex" in Tcl to remove leading and trailing characters from a "start" period

2.3k Views Asked by At

Extracting text parts from a sentence/line using the regex and regsub functions - left and right. For example the line:

I need regsub and/orregex to leave only the snippet between "@".

Staying like this: 12.1.4 the rest can erase all the left and right surplus.

In another scenario, in Bash and not Tcl. I can do it like this:

enter image description here

enter image description here

enter image description here

I am asking this question, more for the sake of teaching. That is, learning to use the native features of this Tcl language instead of relying on the Unix-Like system command itself.

How can I craft a regular expression to execute this command? Thanks in advance ...

2

There are 2 best solutions below

1
On BEST ANSWER

I prefer to think in terms of selecting the text between the @ characters. For that, we use regexp (with a capturing group). In this case a non-greedy inner piece is easiest.

regexp {@(.*?)@} $var -> wantedBit
puts $wantedBit

Note that the -> is a dummy variable name here that takes the whole text of the match (which we are uninterested in).

It is possible to make code that looks more like that sed code with regsub:

set var [regsub {^.*@(.*)@.*$} $var {\1}]

The dialect of regular expressions is slightly different.

2
On

Why the requirement to use a regular expression? This problem can easily be solved without it, using split and lindex:

set var "learning lesson [email protected]@_01.html"
puts [lindex [split $var @] 1]