Regular expression to remove special characters in JSTL tags

前端 未结 1 572
别跟我提以往
别跟我提以往 2020-12-03 09:26

I am working on a Spring application and in JSPX page I need to dynamically load some values from properties page and set them as dropdown using options tag. I need to use

相关标签:
1条回答
  • 2020-12-03 09:35

    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.

    JSTL does not offer another EL function for that. You could just homegrow an EL function yourself which delegates to the regex based String#replaceAll().

    E.g.

    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 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 below:

    <%@taglib uri="http://example.com/functions" prefix="f" %>
    
    ...
    
    ${f:replaceAll(repOption, '[^A-Za-z]', '')}
    

    Or, if you're already on Servlet 3.0 / EL 2.2 or newer (Tomcat 7 or newer), wherein EL started to support invoking methods with arguments, simply directly invoke String#replaceAll() method on the string instance.

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

    See also:

    • How to call parameterized method from JSP using JSTL/EL
    0 讨论(0)
提交回复
热议问题