开发者

Regular expressions: What is the difference between `[0-9]{1,2}` and `^[0-9]{1,2}$`?

开发者 https://www.devze.com 2023-02-25 01:44 出处:网络
What is the difference between [0-9]{1,2} and ^[0-9]{1,2}$? If we remove 开发者_C百科^ and $, what will the effect be in this case?The ^ means that the match shall appear at the beginning of a string

What is the difference between [0-9]{1,2} and ^[0-9]{1,2}$?

If we remove 开发者_C百科^ and $, what will the effect be in this case?


The ^ means that the match shall appear at the beginning of a string, and the $ says that it should match the end of a string.

In your case [0-9]{1,2} will match any number with one or two digits inside any string (e.g. sakdj12lkjad92 will match), while the latter one will only match if the string only contains one or two digits.


Those characters are called anchors and they bind to specific positions in the string. If you're not discussing multi-line regexes, they will bind to the beginning (for ^) and end (for $) of the string.

That means that ^[0-9]{1,2}$ is a string that consists of exactly one or two digits and nothing else, while [0-9]{1,2} is a string of any size containing one or two consecutive digits in it anywhere.

So the first will match 1, 77, 96, 42 and so on. The latter will also match any of those with any amount of text on either side, like paxdiablo is number 1, calling car 54, where are you and so on.

If your regex engine is capable of handling multi-line input, the meaning is usually slightly changed. ^ will bind to either the start of the string or a zero-width point following an end of line character. Similarly, $ will bind to the end of string and any zero-width point before an end on line.

In those cases, if you want to only match the start or end of the string, you'll probably find you can use \A and \Z.


^ means start of string
$ means end of string

[0-9]{1,2} => DEMO

^[0-9]{1,2} => DEMO

0

精彩评论

暂无评论...
验证码 换一张
取 消