Simple question like. What does the regular "a^b" mean and is it possible to find it in any string?

 import re p = re.compile("a^b") p.search("ab") --> None p.search("a^b") --> None p.search("a\nb") --> None 

If such an expression really doesn’t match any string (really, how can the character a occur before the beginning of the string being checked), then why does it compile at all?

Or, to paraphrase, does the meaning of the symbol ^ / $ change depending on its position in the regular expression (not inside the square brackets)? If not, why not?

The question is irrelevant, the python is just an example of sake.

    1 answer 1

    ^ means "the beginning of the line" regardless of which part of the expression occurs. Just like $ - the end of the "string". But there can be several "started" and "ends" in the "string". Take an example (on python, so on python):

     import re p=re.compile("a.*^b",re.M+re.S) p.search("abc\nabcd") --> None p.search("abc\nbcd") --> <_sre.SRE_Match object; span=(0, 5), match='abc\nb'> 

    When compiling an expression, the following flags are specified: re.S forces . Match any characters, including carriage return. re.M makes us consider "string" as "multi-line" - i.e. ^ begins to correspond not only to the beginning of the data, but also to the point after any carriage transfer. So we got that "a" met before the beginning of the line.

    Flags can be set not only by the second compile parameter, but also inside the regular record itself, with constructions like (?sm) . I think the developers of the regulars broke such a deep analysis (there are flags, no, but when they started to act), for the sake of issuing errors like "the beginning of the line can not be here." Actually for this no one runs the risk of treating ^ и $ differently, depending on the position (except for cases with square brackets, of course).

    Regexp101.com example

    • inside [] symbol ^ Does not mean the beginning of the line :) - Grundy
    • one
      @Grundy quote from the TS question: Or, paraphrasing, does the meaning of the ^ / $ symbol change depending on its position in the regular expression (not inside the square brackets) . And under my "depending on the position" of course, means the same thing. - Mike
    • yes :-) before this part I didn’t read the question - Grundy
    • @Mike, thanks. It turns out that I simply did not realize changing a^b to a\\n^b (roughly speaking). C MULTILINE then I was played. - andy.37