How to match numbers ranging from 400 to 550 with regex?

I want to validate a numeric string that must only contain numbers ranging from 400 to 550.

$x = "401";  // valid 
$x = "551";  // invalid 

I want to only match the numbers between 400 and 550.

I tried the following pattern:

if(preg_match_all("/[400-550]+/",$x)); 

But it doesn't work.

What is the regex pattern for matching numbers 400-550?

Answers


A regex-way to validate this range:

\b(?:4[0-9]{2}|5[0-4][0-9]|550)\b

See demo. It will also work in larger texts since \b boundaries are used. In case of whole strings, use ^ and $ around instead of \b.


Just combine in_array() with range(), like this:

if(!in_array($x, range(400, 550)))
   echo "in ";
echo "valid";

Or just do a simple if statement, e.g.

if($x >= 400 && $x <= 550)

Should work :

^((4\d\d)|(5([0-4]\d|50)))$

Try this:

 if(preg_match_all("/(4\d\d|5([0-4]\d|50))/",$x)) { ... }

Test: https://regex101.com/r/zU4vX8/2


Try /(([4][0-9]{2,2})|([5][0-4][0-9])|(550))/ (I haven't tested it). I dont know if there is an easier way.


Unless you have a reason to use a regex, just compare the numbers.

if ($x <= 550 && $x >= 400)

It'll be faster and easier to read than a regex or using array ranges.


The php code:

<?php
$subject = "550";
$pattern = '/4\d\d|5[0-4][0-9]|550/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

Need Your Help

How to search a dict of unicode for a string

python unicode encoding dictionary utf-8

Using python 2.7.4 in Ubuntu 13.10 I'm having my head done in by string encodings.

calling a template function on a auto type-inferred variable in a template class

c++ c++11 gcc compiler-errors auto

This problem occurred in the context of the google test framework with typed test cases. Here inheritance and templates are mixed such that we have to refer to members of the base class via this->....