Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Regular Expressions in JSP EL

Tags:

regex

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?

like image 583
MCS Avatar asked Nov 17 '08 17:11

MCS


People also ask

What is EL expression in JSP?

Advertisements. JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical.

Is El ignored in JSP?

The default mode for JSP pages delivered using a descriptor from Servlet 2.3 or before is to ignore EL expressions; this provides backward compatibility.

What does %s mean in regex?

The Difference Between \s and \s+ For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What does \\ mean in Java regex?

String regex = "\\."; Notice that the regular expression String contains two backslashes after each other, and then a . . The reason is, that first the Java compiler interprets the two \\ characters as an escaped Java String character. After the Java compiler is done, only one \ is left, as \\ means the character \ .


2 Answers

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

like image 66
Giuseppe Avatar answered Oct 07 '22 03:10

Giuseppe


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

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib version="2.1"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">

    <display-name>Acme tags</display-name>
    <short-name>custom</short-name>
    <uri>http://www.acme.com.au</uri>
    <function>
        <name>matches</name>
        <function-class>java.util.regex.Pattern</function-class>
        <function-signature>
            boolean matches(java.lang.String, java.lang.CharSequence)
        </function-signature>
    </function>
</taglib>

Then in your jsp

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

This will work exactly the same as Pattern.match

like image 32
abualy Avatar answered Oct 07 '22 03:10

abualy