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.

  • $\begingroup$ Your question isn't very clear. ^ matches the start and $ the end of the string, so it can only match whole strings. $\endgroup$
    – Veedrac
    Dec 3, 2017 at 15:55
  • $\begingroup$ Yes ^ matched beginning and $ matches end so from that perspective /^(abc)$/ should contain abcdabc because abc is prefix and suffix both, but it only matches abc. Why? $\endgroup$
    – gamedev90
    Dec 3, 2017 at 16:10
  • $\begingroup$ Using that argument xy should match xSy, because x matches xSy and y matches xSy. That's not how regular expressions work; you need to match the whole thing at once. $\endgroup$
    – Veedrac
    Dec 3, 2017 at 17:59
  • $\begingroup$ but /xy/ will match any substring xy because there is no modifier like $, ^, {n} etc $\endgroup$
    – gamedev90
    Dec 5, 2017 at 11:21
  • $\begingroup$ but my question is does /^abc$/ mean starting with abc and ending with abc and only containing abc, or just starting with abc and ending with abc $\endgroup$
    – gamedev90
    Dec 5, 2017 at 11:23

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.