[ACCEPTED]-Using Regular Expressions in JSP EL-el

Accepted answer
Score: 19

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

On the bright side, it's 9 pretty easy to write an EL function that 8 does what you want. You need the function 7 implementation, and a TLD to let your web 6 application know where to find it. Put these 5 together in a JAR and drop it into your 4 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="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">
    <description>Test whether a string matches a regular expression.</description>
    <function-signature>boolean matches(java.lang.String, java.lang.CharSequence)</function-signature>

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

Score: 6

Simply add the following to WEB-INF/tags.tld

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib version="2.1"

    <display-name>Acme tags</display-name>
            boolean matches(java.lang.String, java.lang.CharSequence)

Then 2 in your jsp

<%@taglib uri="http://www.acme.com.au" prefix="custom"%>
custom:matches('aaa.+', someVar) }

This will work exactly the same 1 as Pattern.match

Score: 5

You can use JSTL functions like so -

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

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

Score: 1

for using Pattern.matches inside a jsp page 2 in my case it was enough to call java.util.regex.Pattern.matches(regexString,stringToCompare) because 1 you can't import package in jsp

More Related questions