2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Regular expression to remove special characters in JSTL tags

I need to some way to integrate the regular expression functionality in JSTL.

e.g support the string contain AB then I want to display like A,B or A/B or A B etc.

userimage

I wiil suggest instead of using any JSTL function, you can manipulate the data before publishing to JSP page. I mean if you want to remove special character, then remove from the origin place.

userimage

Before My explanation I need to clear that, If you are thinking to use fn:replace().

The JSTL fn:replace() does not use a regular expression based replacement. It's just an exact charsequence-by-charsequence replacement, exactly like as String#replace() does.

Here is the complete evaluation for your requirement,

package com.example;

public final class Functions {

     private Functions() {

         //

     }

     public static String replaceAll(String string, String pattern, String replacement) {

         return string.replaceAll(pattern, replacement);

     }

}


Which you can register in a /WEB-INF/functions.tld file as follows:

<?xml version="1.0" encoding="UTF-8" ?>

<taglib 

    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"

    version="2.1">


    <display-name>Custom Functions</display-name>    

    <tlib-version>1.0</tlib-version>

    <uri>http://example.com/functions</uri>


    <function>

        <name>replaceAll</name>

        <function-class>com.example.Functions</function-class>

        <function-signature>java.lang.String replaceAll(java.lang.String, java.lang.String, java.lang.String)</function-signature>

    </function>

</taglib>


And finally use as follows:


<%@taglib uri="http://example.com/functions" prefix="f" %>

...

${f:replaceAll(repOption, '[^A-Za-z]', '')}

Answer is