Tcl Source Code

View Ticket
Login
Ticket UUID: 471101
Title: RE \A and ^ don't replace the same
Type: Bug Created on: 2001-10-14 20:02:58
Submitter: hobbs Assigned to: hobbs
Subsystem: 43. Regexp Severity:
Priority: 5 Medium Last modified: 2026-10-10 17:51:51
Status: Open Closed by:
Resolution: None Closed on:
Version: obsolete: 8.3.3
Description:
When no options are specified, \A and ^ should be the 
same, but they don't seem to behave the same:

(hobbs) 79 % regsub -all {\Aa} {aabbcc} {b} r
2
(hobbs) 80 % set r
bbbbcc
(hobbs) 81 % regsub -all {^a} {aabbcc} {b} r
1
(hobbs) 82 % set r
babbcc

whereas \Z seems OK:

(hobbs) 83 % regsub -all {(\Aa|c\Z)} {aabbcc} {b} r
3
(hobbs) 84 % set r
bbbbcb
(hobbs) 85 % regsub -all {(^a|c$)} {aabbcc} {b} r
2
(hobbs) 86 % set r
babbcb
User Comments:
hobbs added on 2001-10-15 03:19:52:
Logged In: YES 
user_id=72656

This is actually ... correct.  The problem is with the 
handling of offsets, and is indicated by the docs for 
regsub -start (which just allows the user to set the 
offset).

-start index
Specifies a character index offset into the string to start 
matching the regular expression at. When using this switch, 
`^' will not match the beginning of the line, and \A will 
still match the start of the string at index. If -indices 
is specified, the indices will be indexed starting from the 
absolute beginning of the input string. index will be 
constrained to the bounds of the input string.

This result is actually the same for 8.2.  I'm not sure 
that this is a great feature, but I think the only way to 
get around it is to get into the guts of the RE.

serhiy.storchaka added on 2026-10-10 17:51:51:

Still the same in 8.6, 9.0 and 9.1. With -all, regexp and regsub restarted matching on the substring after the previous match, so \A matched again at each restart point; ^ was only protected by TCL_REG_NOTBOL. All other engines (PCRE, Perl, Python, Java, Ruby, and PostgreSQL, whose engine is derived from Tcl's) match \A only once.

Word constraints are affected the same way, since they could not see the character before the restart point: regexp -all -inline {\m\w} "ab cd" returns a b c d instead of a c, and \y matches between any two word characters.

Proposed fix in branch regexp-all-search-start: successive matches are searched from the current offset in the whole string, so \A matches only at the start (or at the -start index) and word constraints see the previous character. Tests regexp-29.*. Test regexp-16.4, which expected the old behaviour, is updated. This changes behaviour, so it is proposed for the next feature release, not for backporting. Also fixes [884d0ac78c].