Regex – Using Regular Expressions in JSP EL


In EL expressions, used in a jsp page, strings are taken literally. For example, in the following code snippet

<c:when test="${myvar == 'prefix.*'}">

test does not evaluate to true if the value of myvar is 'prefixxxxx.' Does anyone know if there is a way to have the string interpreted as a regex instead? Does EL have something similar to awk's tilde ~ operator?

Best Solution

While this special case can be handled with the JSTL fn:startsWith function, regular expressions in general seem like very likely tests. It's unfortunate that JSTL doesn't include a function for these.

On the bright side, it's pretty easy to write an EL function that does what you want. You need the function implementation, and a TLD to let your web application know where to find it. Put these together in a JAR and drop it into your WEB-INF/lib directory.

Here's an outline:


import java.util.regex.Pattern;

public class Regexp {

  public static boolean matches(String pattern, CharSequence str) {
    return Pattern.compile(pattern).matcher(str).matches();



<taglib xmlns="" xmlns:xsi="" xsi:schemaLocation="" version="2.0">
    <description>Test whether a string matches a regular expression.</description>
    <function-signature>boolean matches(java.lang.String, java.lang.CharSequence)</function-signature>

Sorry, I didn't test this particular function, but I hope it's enough to point you in the right direction.