regsub(n)
β¨ regsub(n) β¨
okay so bestie, welcome to regsub β a built-in command in the Tcl family, and literally the moment your regex era begins. She does one thing and she does it gorgeously: she goes looking for pattern matches and swaps them out. π
πΈ NAME πΈ
regsub β Perform substitutions based on regular expression pattern matching π
π SYNOPSIS π
regsub ?switches? exp string subSpec ?varName?
π¦ DESCRIPTION π¦
So here's the tea. regsub takes the regular expression exp and matches it against string. Then it either:
- copies
stringinto the variable whose name you handed over asvarName, or - just returns
stringif you didn't pass avarNameat all.
(How regular expression matching actually works is a whole other saga β it lives in the re_syntax reference page. Go read her when you're ready. π«Ά)
Now, if there's a match, then while it's copying string over into varName (or into the result of this command if there's no varName), the part of string that matched exp gets replaced with subSpec. Iconic behaviour honestly.
Here's the substitution cheat sheet, no cap:
- If
subSpeccontains a&or a\0, that bit gets replaced in the substitution with the portion ofstringthat matchedexp. β¨ - If
subSpeccontains a\n, where n is a digit between1and9, it gets replaced with the portion ofstringthat matched the n'th parenthesized subexpression ofexp. π― - You can stack additional backslashes in
subSpecto stop&,\0,\nand backslashes from being interpreted specially.
β οΈ Okay genuine warning time, bestie: backslashes insubSpectend to interact badly with the Tcl parser's own use of backslashes. It's generally safest to wrapsubSpecin braces if it includes backslashes. Do not skip this. π
β¨ OPTIONS β¨
If the initial arguments to regsub start with -, they get treated as switches. These are the switches currently supported:
-allβ Every range instringthat matchesexpgets found, and the substitution is performed for each one of those ranges. Without this switch, only the first matching range gets found and substituted (basic behaviour, lowkey). If-allis specified, then&and\nsequences are handled for each substitution using the information from the corresponding match. π₯-commandβ This changes howsubSpecis handled: it's no longer treated as a template for a substitution string, and the substrings&and\nno longer have any special meaning. Instead,subSpecmust be a command prefix, that is, a non-empty list. The substring ofstringthat matchesexp, and then each substring that matches each capturing sub-RE withinexp, get appended as additional elements to that list. (The items appended to the list are much like whatregexp -inlinewould return, iykyk.) The completed list is then evaluated as a Tcl command, and the result of that command is the substitution string. Any error or exception from that command evaluation becomes an error or exception from theregsubcommand. π- If
-allis not also given, the command callback will be invoked at most once (exactly when the regular expression matches). - If
-allis given, the command callback will be invoked for each matched location, in sequence. - The exact location indices that matched are not made available to the script.
- See EXAMPLES below for illustrative cases. π
- If
-expandedβ Enables use of the expanded regular expression syntax, where whitespace and comments are ignored. This is the same as specifying the(?x)embedded option (see there_syntaxmanual page).-lineβ Enables newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning. With this flag,[^bracket expressions and.never match newline,^matches an empty string after any newline in addition to its normal function, and$matches an empty string before any newline in addition to its normal function. This flag is equivalent to specifying both-linestopand-lineanchor, or the(?n)embedded option (see there_syntaxmanual page).-linestopβ Changes the behavior of[^bracket expressions and.so that they stop at newlines. This is the same as specifying the(?p)embedded option (see there_syntaxmanual page).-lineanchorβ Changes the behavior of^and$(the "anchors") so they match the beginning and end of a line respectively. This is the same as specifying the(?w)embedded option (see there_syntaxmanual page).-nocaseβ Upper-case characters instringwill be converted to lower-case before matching againstexp. However, substitutions specified bysubSpecuse the original unconverted form ofstring. π-startindex β Specifies a character index offset into the string to start matching the regular expression at. The index value is interpreted in the same manner as the index argument tostring index. When using this switch,^will not match the beginning of the line, and\Awill still match the start of the string at index. index will be constrained to the bounds of the input string.--β Marks the end of switches. The argument following this one will be treated asexpeven if it starts with a-.
And now the return value moment: if varName is supplied, the command returns a count of the number of matching ranges that were found and replaced. Otherwise, the string after replacement is returned. π
See the manual entry for regexp for the deets on how regular expressions get interpreted.
π EXAMPLES π
Replace (in the string in variable string) every instance of foo which is a word by itself with bar:
regsub -all {\mfoo\M} $string bar string
or (using the "basic regular expression" syntax):
regsub -all {(?b)\<foo\>} $string bar string
Insert double-quotes around the first instance of the word interesting, however it is capitalized:
regsub -nocase {\yinteresting\y} $string {"&"} string
Convert all non-ASCII and Tcl-significant characters into \u escape sequences by using regsub and subst in combination:
# This RE is just a character class for almost everything "bad"
set RE {[][{};#\\\$ \r\t\u0080-\uffff]}
# We will substitute with a fragment of Tcl script in brackets
set substitution {[format \\\\u%04x [scan "\\&" %c]]}
# Now we apply the substitution to get a subst-string that
# will perform the computational parts of the conversion. Note
# that newline is handled specially through string map since
# backslash-newline is a special sequence.
set quoted [subst [string map {\n {\\u000a}} \
[regsub -all $RE $string $substitution]]]
The above operation can be done using regsub -command instead, which is often faster. (A full pre-computed string map would be faster still, but the cost of computing the map for a transformation as complex as this can be quite large.) π«Ά
# This RE is just a character class for everything "bad"
set RE {[][{};#\\\$\s\u0080-\uffff]}
# This encodes what the RE described above matches
proc encodeChar {ch} {
# newline is handled specially since backslash-newline is a
# special sequence.
if {$ch eq "\n"} {
return "\\u000a"
}
# No point in writing this as a one-liner
scan $ch %c charNumber
format "\\u%04x" $charNumber
}
set quoted [regsub -all -command $RE $string encodeChar]
Decoding a URL-encoded string using regsub -command, a lambda term and the apply command:
# Match one of the sequences in a URL-encoded string that needs
# fixing, converting + to space and %XX to the right character
# (e.g., %7e becomes ~)
set RE {(\+)|%([0-9A-Fa-f]{2})}
# Note that -command uses a command prefix, not a command name
set decoded [regsub -all -command $RE $string {apply {{- p h} {
# + is a special case; handle directly
if {$p eq "+"} {
return " "
}
# convert hex to a char
scan $h %x charNumber
format %c $charNumber
}}}]
The -command option can also be useful for restricting the range of commands such as string totitle:
set message "the quIck broWn fOX JUmped oVer the laZy dogS..."
puts [regsub -all -command {\w+} $message {string totitle}]
# β The Quick Brown Fox Jumped Over The Lazy Dogs..
She really ate that one. π
π§ SEE ALSO π§
regexp(n), re_syntax(n), subst(n), string(n)
β KEYWORDS β
match, pattern, quoting, regular expression, substitution
and that's the whole vibe, bestie π¦ β this page is from the Tcl Built-In Commands manual, version 8.3, dated regsub(n), so go forth and substitute responsibly. mwah π
π¦ where this page comes from
- alpine 3.23: tcl9-doc 9.0.3-r0 Β· TCL
- alpine 3.24: tcl9-doc 9.0.3-r2 Β· TCL
- fedora 43: tcl-doc 1:9.0.2-1.fc43 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- nixos 26.05: tcl 9.0.3
- nixpkgs unstable: tcl 9.1.0
- Copyright (c) 1993 The Regents of the University of California
- Copyright (c) 1994-1996 Sun Microsystems, Inc
- Copyright (c) 2000 Scriptics Corporation
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms