Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

php - What regex can I use to validate a number between 0 and 255?

I want to validate number in range of 0-255

I have this expression

'/^([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5])$/'

But this accepts any number... And this works:

'/(^[0-1]?[0-9]?[0-9]$)|(^[2][0-4][0-9]$)|(^25[0-5]$)/'

why do I have to have ^ and $ for each option?

edit: I have it, but I cannot answer my question, so - ^ and $ have higher priority than |, so /^(...)$/ helped

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: @alex's answer is the way to go. Validating a number range with regex is like using a jackhammer to catch a fly.

But nevertheless I wanted to provide an explanation for this "problem".


You don't have to, you just have to group it correctly, which means you have to group the alternation:

'/^(([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5]))$/'
// ^                                             ^

Otherwise the expression will be interpreted as follows (logically)

(^number) OR (number) OR (number$)

With the brackets, it will be

^(number OR number OR number)$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...