TCL Regular expression to trim the string from specific special character

Viewed 184

My TCL Regexp is as below

regexp {((\d:[\da-zA-Z]+))} "3001:470:8865:2E01::190:201" out

current value of out is the complete string

3001:470:8865:2E01::190:201

I want the string before ::

3001:470:8865:2E01
4 Answers

You can match single-colon separated alphanumeric char chunks at the start of a string:

regexp {^\w+(?::\w+)*} "3001:470:8865:2E01::190:201" out
puts $out

Output: 3001:470:8865:2E01

See the Tcl demo online and the regex demo. Details:

  • ^ - start of string
  • \w+ - one or more letters, digits or underscores
  • (?::\w+)* - zero or more occurrences of a colon and then one or more letters, digits or underscores.

You might also consider precising \w pattern to [\dA-Za-z] in case you want to match letters and digits only, and replace the first \w+ with \d+:

regexp {\d+(?::[\dA-Za-z]+)*} "3001:470:8865:2E01::190:201" out

See this Tcl demo and this regex demo.

Alternately, remove the stuff you don't want:

regsub {::.*} "3001:470:8865:2E01::190:201" {} out

puts $out  ;# ==> 3001:470:8865:2E01

To stop the RE at ::, use a forward lookahead:

regexp {.*(?=::)} "3001:470:8865:2E01::190:201" out

The out variable is not written to if the RE does not match.

Related