tags:

views:

5064

answers:

2

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?

+2  A: 

You can use JSTL functions like so -

<c:when test="${fn:startsWith(myVar, 'prefix')}">

Take a look: http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fn/tld-summary.html

lucas
+6  A: 

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:

com/x/taglib/core/Regexp.java:

import java.util.regex.Pattern;

public class Regexp {

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

}

META-INF/x-c.tld:

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
  <tlib-version>1.0</tlib-version>
  <short-name>x-c</short-name>
  <uri>http://dev.x.com/taglib/core/1.0&lt;/uri&gt;
  <function>
    <description>Test whether a string matches a regular expression.</description>
    <display-name>Matches</display-name>
    <name>matches</name>
    <function-class>com.x.taglib.core.Regexp</function-class>
    <function-signature>boolean matches(java.lang.String, java.lang.CharSequence)</function-signature>
  </function>
</taglib>

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

erickson