Regular Expression: +$ VS *$ VS none

后端 未结 4 1181
半阙折子戏
半阙折子戏 2021-02-08 08:54

In regular expressions, what is the difference between ^[a-zA-Z]+$ and ^[a-zA-Z]*$. Also would I be able to not include it at all, either with ^[

4条回答
  •  不思量自难忘°
    2021-02-08 09:36

    ^ and $ are anchors. They do not match anything, all they do is placing the at a particular place in the input.

    • When you have ^, you tell the engine that whatever follows it must start at the beginning of the line
    • When you have $, you tell the engine that whatever precedes it must start at the end of the line
    • When you have both ^ and $ you tell the engine that whatever is in between them must cover the entire line end-to-end.

    Now it should be easy to understand the difference between [a-zA-Z]* and [a-zA-Z]+ placed between the anchors: the one with the asterisk allows empty lines, while the one with the plus insists on matching at least one character.

    It should also be easy to understand what happens when you place only one anchor: essentially, you are letting the engine ignore the beginning (when ^ is missing) or the end of the line (when $ is missing) when looking for a match.

提交回复
热议问题