Regex check minimum and maximum length
Using Regular expression( Regex ), We can check whether the given string has minimum no. of characters or whether it is inside specified range etc. We use ^ and $ to count length of string from the beginning to the end. For example, following regex will match a string which has 5 characters:
So, if we want check whether the given string length is in the range between 5 to 7, we use:
Its okay, but how we use this in real time, huh? There will be slight changes between the scripts in implementing regex. Below i have given you examples in javascript and php.
/^[a-zA-Z]{5}$/
So, if we want check whether the given string length is in the range between 5 to 7, we use:
/^[a-zA-Z]{5,7}$/
Its okay, but how we use this in real time, huh? There will be slight changes between the scripts in implementing regex. Below i have given you examples in javascript and php.
Check minimum and maximum length in Javascript:
<script type="text/javascript">
var str='webdevelopmentscripts.com';
var regexRange=/^[a-zA-Z]{5,7}$/;
if(regexRange.test(str)==true)
alert('Inside given range');
else
alert('Exceeds given range');
</script>
var str='webdevelopmentscripts.com';
var regexRange=/^[a-zA-Z]{5,7}$/;
if(regexRange.test(str)==true)
alert('Inside given range');
else
alert('Exceeds given range');
</script>
Check minimum and maximum length in PHP:
<?php
$str="webdevelopmentscripts.com";
if(preg_match('/^[a-zA-Z]{5,7}$/',$str))
echo 'Inside given range';
else
echo 'Exceeds given range';
?>
$str="webdevelopmentscripts.com";
if(preg_match('/^[a-zA-Z]{5,7}$/',$str))
echo 'Inside given range';
else
echo 'Exceeds given range';
?>
Comments (0)