Number of occurences using {}



The curly bracket can be used to define the number of occurrences of the preceding character.

{n} indicates exactly n occurrence of the preceding character
{n1, n2} indicates that the number of occurrence of the preceding character should be between n1 and n2 times
{n,} indicates n or more occurrence of the preceding character

Some quick examples

Pattern fo{2}d matches food but not fod, foood or fud.
Pattern fo{2,3}d matches food and foood but not, fod or fooood.
Pattern fo{2,}d matches foood, food but not, fod .


We will now work in a complete example.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Javascript Regular Expression Example 8
Number of occurrences with {}
********************************************************
*/
var pattern1=new RegExp("fo{2}d");
var pattern2=new RegExp("fo{2,3}d");
var pattern3=new RegExp("fo{2,}d");
var string1 = new Array(4);
string1[0] = "food";
string1[1] = "fod";
string1[2] = "foood";
string1[3] = "fooood";
var i;
for(i=0; i<=3; i++)
{
if (pattern1.test(string1[i]))
{
document.write(string1[i], " -> match found with fo{2}d ","<br\>");
}
else
{
document.write(string1[i], " -> match not found with fo{2}d","<br\>");
}
}
for(i=0; i<=3; i++)
{
if (pattern2.test(string1[i]))
{
document.write(string1[i], " -> match found with fo{2,3}d","<br\>");
}
else
{
document.write(string1[i], " -> match not found with fo{2,3}d","<br\>");
}
}
for(i=0; i<=3; i++)
{
if (pattern3.test(string1[i]))
{
document.write(string1[i], " -> match found with fo{2,}d ","<br\>");
}
else
{
document.write(string1[i], " -> match not found with fo{2,}d ","<br\>");
}
}
//-->
</script>
</body>
</html>

Try this Example online


You can try this example online at - here .


This script gives the following output.

food -> match found with fo{2}d
fod -> match not found with fo{2}d
foood -> match not found with fo{2}d
fooood -> match not found with fo{2}d
food -> match found with fo{2,3}d
fod -> match not found with fo{2,3}d
foood -> match found with fo{2,3}d
fooood -> match not found with fo{2,3}d
food -> match found with fo{2,}d
fod -> match not found with fo{2,}d
foood -> match found with fo{2,}d
fooood -> match found with fo{2,}d

It is time you give slight stress on your mind on some simple questions. The purpose of these questions is more to get the things settled in your mind than to stress you. It will help you memorize some basic regular expression constructs.