在JSP EL中使用正则表达式

MCS*_*MCS 11 regex jsp el

在jsp页面中使用的EL表达式中,字符串是字面意思的.例如,在以下代码段中

<c:when test="${myvar == 'prefix.*'}">
Run Code Online (Sandbox Code Playgroud)

如果myvar的值为'prefixxxxx',则test不会计算为true.有没有人知道是否有办法将字符串解释为正则表达式?EL有类似于awk的波浪号〜运算符的东西吗?

eri*_*son 19

虽然这个特殊情况可以使用JSTL fn:startsWith函数来处理,但正则表达式通常看起来很可能是测试.不幸的是,JSTL没有为这些功能提供功能.

从好的方面来说,编写一个能够满足您需求的EL功能非常容易.您需要功能实现和TLD,以便让您的Web应用程序知道在哪里找到它.将它们放在JAR中并将其放入WEB-INF/lib目录中.

这是一个大纲:

COM/X /标签库/核心/ 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();
  }

}
Run Code Online (Sandbox Code Playgroud)

META-INF/xc.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</uri>
  <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>
Run Code Online (Sandbox Code Playgroud)

对不起,我没有测试这个特殊的功能,但我希望它足以指出你正确的方向.


小智 7

只需将以下内容添加到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>
Run Code Online (Sandbox Code Playgroud)

然后在你的jsp中

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

这将与Pattern.match完全相同


luc*_*cas 5

您可以像这样使用JSTL函数 -

<c:when test="${fn:startsWith(myVar, 'prefix')}">
Run Code Online (Sandbox Code Playgroud)

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