The regex /^(abc)$/
matches abc
but why not abcdabc
, abcdabc
also begins with abc
and ends with abc
.
I am not sure about the semantics of this regex. Any explanation is welcome.
First of all, what we usually call Regex, for instance, in the context of programming languages, is not the same as pure regular expressions. That should not come as a surprise: all computational models have to be adapted to the real world to be made useful. In this case, besides being enriched by features that just enlarge the range of languages it can specify (such as numbered back references), Regex has other features that would require a completely different set of tools to be formalized properly.
What comes after ^
will not be matched to a prefix of the input string. What happens is that ^
is a reference to an event (as is $
, they are called anchors). In abstract terms, you can think of the input of a Regex as continuous stream of symbols, unbounded, that is divided in units of limited size, separated from each other by a special symbol. Where should the matching process begin? This is where anchors come to the rescue.
In this context, ^
refers to the event of finding the special symbol, and forcing the Regex to match beginning with whatever comes right after, instead of $\unicode{x2013}$ for instance $\unicode{x2013}$ continuously trying to match a string starting with each symbol from the input, and backtracking to the next, in case of failure.
What the actual input unit is, pragmatically, depends on the context of application of the formalism. Usually we are talking about lines in a text file, separated by line break characters, or the successive contents of an input buffer.
^
matches the start and$
the end of the string, so it can only match whole strings. $\endgroup$^
matched beginning and$
matches end so from that perspective/^(abc)$/
should containabcdabc
becauseabc
is prefix and suffix both, but it only matchesabc
. Why? $\endgroup$xy
should matchxSy
, becausex
matchesxSy
andy
matchesxSy
. That's not how regular expressions work; you need to match the whole thing at once. $\endgroup$/xy/
will match any substring xy because there is no modifier like $, ^, {n} etc $\endgroup$/^abc$/
mean starting with abc and ending with abc and only containing abc, or just starting with abc and ending with abc $\endgroup$