Tcl regular expressions
last modified November 24, 2026 Tcl 8.6
Tcl uses regular expressions through two commands: regexp finds a
pattern in a string and regsub replaces it. Both use the same
regular expression engine, which supports character classes, quantifiers,
groups, anchors and backreferences. The engine is the Advanced Regular
Expressions (ARE) dialect, a superset of POSIX extended expressions with a few
Perl-like conveniences.
Regular expressions are the right tool for pulling fields out of log lines, checking the shape of user input and rewriting text. This article starts with a single match, then adds captures, list results, index results, anchors, substitution and two applied examples.
regexp basics and return values
The simplest form is regexp pattern string. It returns 1 when the
pattern occurs anywhere in the string and 0 when it does not. Without switches
the match may start at any position, and the pattern is literal except for the
regular expression metacharacters.
set line "ERROR 2026-11-24 disk full on /dev/sda1"
puts "error: [regexp {ERROR} $line]"
puts "warning: [regexp {WARNING} $line]"
puts "nocase: [regexp -nocase {error} $line]"
puts "start: [regexp {^ERROR} $line]"
puts "digits: [regexp {\d+} $line]"
puts "letters: [regexp {[A-Z]+} $line]"
The first search succeeds and the second fails. -nocase makes the
match case insensitive, and ^ anchors the pattern at the start of
the string. The last two lines show a character class and a shorthand class:
\d matches a digit, while [A-Z] matches an uppercase
letter. The pattern is braced so that Tcl does not substitute anything inside
it; backslashes reach the regular expression engine unchanged.
$ tclsh basics.tcl error: 1 warning: 0 nocase: 1 start: 1 digits: 1 letters: 1
Captures and match variables
Parentheses around part of a pattern create a capture group. When
regexp is given extra variable names, the first receives the whole
match and each following name receives one group, in order. The command still
returns 1 or 0, so it is usually placed in an if condition.
set line "2026-11-24 09:15:02 ERROR disk full"
set pattern {(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) (\w+)}
if {[regexp $pattern $line whole year month day hour minute second level]} {
puts "whole: $whole"
puts "date: $year-$month-$day"
puts "time: $hour:$minute:$second"
puts "level: $level"
}
set group "untouched"
if {![regexp {WARNING (\w+)} $line group]} {
puts "group: '$group' (no match, variable unchanged)"
}
The pattern has seven groups and the command has eight variable names after the
string. The whole match is 2026-11-24 09:15:02 ERROR, and the
groups split it into date, time and level. The second call fails, and Tcl
leaves the variable untouched rather than clearing it, which is why it still
contains the text set before the call. Initializing result variables before a
match is therefore a good habit.
$ tclsh captures.tcl whole: 2026-11-24 09:15:02 ERROR date: 2026-11-24 time: 09:15:02 level: ERROR group: 'untouched' (no match, variable unchanged)
-inline
Passing a long list of variable names is clumsy when the result is used
immediately. The -inline switch makes regexp return a
list instead: the whole match followed by the captured groups. With
-all as well, it returns every match. On failure the result is an
empty list.
set line "user=jane role=admin host=web01"
set pairs [regexp -inline -all {\w+=\w+} $line]
puts "pairs: $pairs"
foreach pair $pairs {
lassign [split $pair =] key value
puts " $key -> $value"
}
set parts [regexp -inline {(\w+)=(\w+)} $line]
puts "first match with groups: $parts"
The first call returns three whole matches because the pattern has no groups
and -all is present. The second call has two groups, so its result
is a four element list: user=jane, user,
jane. That flattening is convenient for short strings but needs
care when the number of groups is not fixed; a variable list, as in the
previous section, is clearer for records with many fields.
$ tclsh inline.tcl pairs: user=jane role=admin host=web01 user -> jane role -> admin host -> web01 first match with groups: user=jane user jane
-all
Without -inline, -all makes regexp
return the number of matches instead of stopping at the first one. Combining
the two switches collects the matching substrings in a list. The next script
counts log levels and extracts IP addresses from a line.
set log "2026-11-24 09:00:01 ERROR disk full
2026-11-24 09:00:05 WARNING memory low
2026-11-24 09:01:12 ERROR write failed"
puts "errors: [regexp -all {ERROR} $log]"
puts "levels: [regexp -all -inline {(ERROR|WARNING)} $log]"
set text "10.0.0.1 10.0.0.22 192.168.1.5"
puts "addresses: [regexp -all -inline {\d+\.\d+\.\d+\.\d+} $text]"
set fields [regexp -all -inline {(\d{2}):(\d{2}):(\d{2})} $log]
puts "fields: $fields"
puts "count: [expr {[llength $fields] / 4}]"
The first count is 2 because only two lines contain ERROR. The
second result repeats each whole match followed by its group, so every level
name appears twice; -all -inline does not return a list of lists.
The time extraction returns three matches, each with three groups, which is
twelve elements. Dividing the list length by four recovers the number of
matches.
$ tclsh all.tcl errors: 2 levels: ERROR ERROR WARNING WARNING ERROR ERROR addresses: 10.0.0.1 10.0.0.22 192.168.1.5 fields: 09:00:01 09 00 01 09:00:05 09 00 05 09:01:12 09 01 12 count: 3
-indices
Sometimes the matched text is not enough; the surrounding string or the exact
position is needed. The -indices switch makes every result variable
hold a two element list of start and end indices instead of the text. The end
index is inclusive, and a group that did not participate in the match is
reported as -1 -1.
set line "status=200 path=/index.html"
regexp -indices {status=(\d+)} $line whole code
puts "whole: $whole"
puts "code: $code"
puts "text: '[string range $line [lindex $code 0] [lindex $code 1]]'"
regexp -indices {path=(\S+)} $line whole path
puts "path: $path"
puts "value: '[string range $line [lindex $path 0] [lindex $path 1]]'"
set absent "untouched"
regexp -indices {missing} $line absent
puts "no match: $absent"
The status digits occupy positions 7 through 9, so string range
with those two indices returns 200. The path value starts at 16
and ends at 26, which includes the leading slash. The failed call leaves the
variable alone again, so a result variable that should be checked must be
initialized first. Index results are the usual way to highlight a match in an
editor or a text widget.
$ tclsh indices.tcl whole: 0 9 code: 7 9 text: '200' path: 16 26 value: '/index.html' no match: untouched
Anchors and -lineanchor
By default ^ matches the start of the whole string and
$ matches its end. The -lineanchor switch changes both
to match at line boundaries, so a pattern can test one line of a multi-line
value. The related -linestop switch stops . and
bracket expressions at newlines.
set text "first line
second line
third line"
puts "default ^second: [regexp {^second} $text]"
puts "lineanchor ^second: [regexp -lineanchor {^second} $text]"
puts "default ^first line\$: [regexp {^first line$} $text]"
puts "lineanchor first line: [regexp -lineanchor {^first line$} $text]"
puts "first words: [regexp -lineanchor -all -inline {^\w+} $text]"
puts "last words: [regexp -lineanchor -all -inline {\w+$} $text]"
puts "anchored whole: [regexp {^\w+ line$} $text]"
The first test fails because second is not at the start of the
whole string. With -lineanchor it succeeds, because the second line
starts with that word. The same difference appears for $: the
pattern ^first line$ describes the entire string under the default
rules, but one line under -lineanchor. The final test returns 0
because the string has three lines and the pattern allows only one. That
distinction is the most common source of surprising anchor results.
$ tclsh anchors.tcl default ^second: 0 lineanchor ^second: 1 default ^first line$: 0 lineanchor first line: 1 first words: first second third last words: line line line anchored whole: 0
regsub and backreferences
The regsub command replaces matches. Its form is
regsub ?switches? pattern string replacement ?varName?. In the
replacement, & stands for the whole match, \1 to
\9 stand for capture groups, and a backslash escapes a literal
ampersand or backslash. Without a variable name the command returns the new
string.
set text "The quick brown fox jumps over the lazy dog"
puts [regsub {quick} $text "slow"]
puts [regsub {(\w+) (\w+)} "Jane Doe" {\2, \1}]
puts [regsub -all {o} $text 0]
set replacements [regsub -all {\s+} " alpha beta gamma " " " collapsed]
puts "collapsed: '$collapsed'"
puts "replacements: $replacements"
puts [regsub {(\w+)@([\w.]+)} "mail jane@example.com" {\2 for \1}]
puts [regsub -all {(\d+)-(\d+)} "10-20 30-40" {\2-\1}]
The first replacement changes one word. The second swaps two captured words and
inserts a comma. Replacing every o with a zero shows that a plain
string is a valid replacement. The whitespace example has a variable name, and
that changes the return value: the new string is stored in
collapsed, while the command returns the number of substitutions,
which is 4. The last two lines show backreferences in an email rewrite and a
repeated range swap. The Tcl regsub command page
documents the remaining switches.
$ tclsh substitutions.tcl The slow brown fox jumps over the lazy dog Doe, Jane The quick br0wn f0x jumps 0ver the lazy d0g collapsed: ' alpha beta gamma ' replacements: 4 mail example.com for jane 20-10 40-30
Validating input
A regular expression can check the shape of a value before it is stored or passed to another command. Anchor the pattern at both ends so that a valid prefix does not make the whole value valid, and use a character class for each position. The following script checks email addresses and dotted IP addresses.
set emails {
jane@example.com
jane.example.com
jane@example
@example.com
jane.doe+news@mail.example.org
}
set email_pattern {^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$}
foreach value $emails {
if {[regexp $email_pattern $value]} {
puts "valid email: $value"
} else {
puts "invalid email: $value"
}
}
set addresses {10.0.0.1 999.1.2.3 192.168.1 192.168.1.20}
foreach value $addresses {
if {[regexp {^(\d{1,3}\.){3}\d{1,3}$} $value]} {
puts "valid address: $value"
} else {
puts "bad address: $value"
}
}
The email pattern requires at least one character before the at sign, a domain
with at least one dot, and a final part of two or more letters. It rejects the
bare domain, the missing domain part and the leading at sign. The address
pattern accepts one to three digits in each of four groups, so
192.168.1 is rejected. It still accepts 999.1.2.3,
because a regular expression checks the shape and not the numeric range; a
second check with split and expr is needed for that.
$ tclsh validate.tcl valid email: jane@example.com invalid email: jane.example.com invalid email: jane@example invalid email: @example.com valid email: jane.doe+news@mail.example.org valid address: 10.0.0.1 valid address: 999.1.2.3 bad address: 192.168.1 valid address: 192.168.1.20
Parsing log lines into a dictionary
A log line is a record with a fixed prefix and a free-form message. One anchored pattern can split it into date, time, level and message, after which each record becomes a dictionary. The dictionaries can be collected in a list, counted, filtered or rendered as a table. This example parses four lines and counts the levels.
set log {
2026-11-24 09:00:01 ERROR disk full on /dev/sda1
2026-11-24 09:00:05 WARNING memory low
2026-11-24 09:01:12 INFO backup finished
2026-11-24 09:02:44 ERROR write failed on /dev/sdb2
}
set pattern {^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+)\s+(.*)$}
set entries {}
set counts [dict create]
foreach line [split [string trim $log] \n] {
if {![regexp $pattern $line whole date time level message]} {
continue
}
lappend entries [dict create date $date time $time \
level $level message $message]
dict incr counts $level
}
puts "parsed [llength $entries] lines"
foreach entry $entries {
puts "[dict get $entry time] [dict get $entry level]: [dict get $entry message]"
}
puts "counts: $counts"
puts "errors: [dict get $counts ERROR]"
set first [lindex $entries 0]
puts "first date: [dict get $first date]"
The pattern anchors the date and time with fixed digit counts, takes the level
as a word, and gives the rest of the line to .*. Because the
message group can contain spaces and slashes, it needs no further splitting.
Lines that do not match are skipped with continue, which keeps a
single malformed line from stopping the whole import. The counts dictionary is
keyed by level, so a report can ask for one level directly. The
Tcl regexp command page lists the switches used
above.
$ tclsh logdict.tcl parsed 4 lines 09:00:01 ERROR: disk full on /dev/sda1 09:00:05 WARNING: memory low 09:01:12 INFO: backup finished 09:02:44 ERROR: write failed on /dev/sdb2 counts: ERROR 2 WARNING 1 INFO 1 errors: 2 first date: 2026-11-24
Source
The Tcl 8.6 manual describes the commands and the regular expression syntax they share. The syntax page is the reference for classes, quantifiers and anchors; the two command pages list the switches.
This article matched text with regexp, captured groups into
variables, collected matches with -inline and -all,
located them with -indices, used line anchors and rewrote text with
regsub. It ended with input validation and a log parser that builds
dictionaries. The Tcl string command page covers the
simpler text operations, and Tcl files and directories
shows how to read the log file that such a parser consumes.
Author
List all Tcl Tutorials.