Scripting

JSP RegEX fails with error Unexpected quantifier

JSP RegEX fails with error Unexpected quantifier

This is a quick article to explain about JSP RegEX fails with error Unexpected quantifier

Scenario:

You have a JSP page that has been running for a long while.  All of sudden you notice its failing resulting in unexpected behavior. Upon troubleshooting you learn that the JSP page fails while create a New RegEx object.

Error:

When you enable Try & Catch exception in JSP you’ll get the error message “Unexpected quantifier”  as  given below:

JSP Code to catch the exception:

<html>
  <script type="text/javascript">
    try{
        var mywebsites = "*.TestSite.com|*.TestSite.com|*.TestSite.com| www.mp3.com | https://www.newmeetings.com";
        var mywebsitesRegex = new RegExp("(" + mywebsites + ")$", "i");
    }
    catch(e) {
      alert(e.message);
    }
    
    alert("mywebsitesRegex = " + mywebsitesRegex);
  </script>
</html>

Results:

---------------------------
Microsoft Internet Explorer
---------------------------
Unexpected quantifier
---------------------------
OK
---------------------------

Cause:

The error message “Unexpected quantifier”  usually refers to the special characters that are being considered as quantifiers in Regular Expression of JSP and they need to be escaped with “\” two backward slashes.  The special characters “*+.?|[]{}()” are considered to be quantifiers.

Fix:

To fix the “Unexpected quantifier”  escape all of the regular expression quantifier special characters with double backward slashes as shown below:

<html>
  <script type="text/javascript">
    try{
        var mywebsites = "*.TestSite.com|*.TestSite.com|*.TestSite.com| www.mp3.com | https://www.newmeetings.com";
        mywebsites = mywebsites.replace(/([*+.?|\\\[\]{}()])/g, '\\$1');
        var mywebsitesRegex = new RegExp("(" + mywebsites + ")$", "i");
    }
    catch(e) {
      alert(e.message);
    }
    
    alert("mywebsitesRegex = " + mywebsitesRegex);
  </script>
</html>

Results:

---------------------------
Message from webpage
---------------------------
mywebsitesRegex&nbsp; = /(\*\.TestSite\.com\|\*\.TestSite\.com\|\*\.TestSite\.com\| www\.mp3\.com \| https:\/\/www\.newmeetings\.com)$/i
---------------------------
OK
---------------------------
Advertisements