Match any string containing a sequence of two to three p's.

To match any string containing a sequence of two to three p's with JavaScript RegExp, use the p{2,3} quantifier. This pattern matches exactly 2 or 3 consecutive occurrences of the letter "p".

Syntax

/p{2,3}/flags

Where {2,3} specifies the minimum (2) and maximum (3) number of consecutive p's to match.

Example: Matching 2-3 Consecutive p's

<html>
<head>
    <title>JavaScript Regular Expression</title>
</head>
<body>
    <script>
        var str = "apple pepper hippopotamus p programming";
        var reg = /p{2,3}/g;
        var matches = str.match(reg);
        
        document.write("Original string: " + str + "<br>");
        document.write("Matches found: " + matches + "<br>");
        document.write("Number of matches: " + matches.length);
    </script>
</body>
</html>
Original string: apple pepper hippopotamus p programming
Matches found: pp,ppp,pp
Number of matches: 3

Testing Different Cases

<html>
<head>
    <title>Testing p{2,3} Pattern</title>
</head>
<body>
    <script>
        var testStrings = [
            "apple",        // contains "pp" (2 p's)
            "pepper",       // contains "pp" (2 p's)  
            "puppy",        // contains "pp" (2 p's)
            "happy",        // contains "pp" (2 p's)
            "hippo",        // contains "pp" (2 p's)
            "pppear",       // contains "ppp" (3 p's)
            "programming",  // single p's only
            "peace"         // single p only
        ];
        
        var pattern = /p{2,3}/g;
        
        testStrings.forEach(function(str) {
            var matches = str.match(pattern);
            document.write(str + " ? " + (matches ? matches.join(", ") : "No match") + "<br>");
        });
    </script>
</body>
</html>
apple ? pp
pepper ? pp
puppy ? pp
happy ? pp
hippo ? pp
pppear ? ppp
programming ? No match
peace ? No match

Key Points

  • p{2,3} matches exactly 2 or 3 consecutive p's
  • Single p's or sequences longer than 3 p's won't match the full pattern
  • Use the g flag to find all matches in a string
  • The pattern is case-sensitive by default

Conclusion

The p{2,3} quantifier effectively matches strings containing 2 to 3 consecutive p's. Use this pattern when you need to find words with double or triple p's like "apple" or "pepper".

Updated on: 2026-03-15T23:18:59+05:30

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements