I always thought in regex, ^ and # like ‘verb’ in must follow something,
such as ^a, line begin with a, or #a, and line end with a, But ^# to me, like # is not a ‘verb’ in this case, like a is a object of the verb ‘^’
Is there anyone can give me a better explanation about this?
I’m going out on a limb here and I’m guessing you actually want to ask why
^$matches the empty line.The key to understanding this is that not everything a regex matches must actually be a character (or characters), it can just as well be a position in the string. Regex tokens that match positions are called “anchors” or “assertions”. They don’t actually consume any text, they just make sure that the regex engine currenty is at a certain position in the string.
So, for example,
^matches if the regex engine is currently at the start of the string. In some circumstances, depending on the current settings, it may also match at the start of the current line. In any case it matches before the first character.Similarly,
$matches at the end of the string (or line); more precisely, it matches before the terminating linefeed, if there is one.Therefore,
^$only matches if there are no characters between the start of the string/line and the end of the string/line.