Search code examples
regextclregsub

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


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 ...


Solution

  • 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.