11

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

<c:when test="${myvar == 'prefix.*'}">

如果 myvar 的值为“prefixxxxx”,则 test 不会评估为 true。有谁知道是否有办法将字符串解释为正则表达式?EL 是否有类似于 awk 的波浪号 ~ 运算符的东西?

4

4 回答 4

19

虽然可以使用 JSTLfn:startsWith函数处理这种特殊情况,但通常正则表达式似乎很可能是测试。不幸的是,JSTL 没有包含这些功能。

从好的方面来说,编写一个 EL 函数来做你想做的事情是很容易的。您需要函数实现和 TLD 来让您的 Web 应用程序知道在哪里可以找到它。将它们放在一个 JAR 中并将其放入您的 WEB-INF/lib 目录。

这是一个大纲:

com/x/taglib/core/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();
  }

}

元信息/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>

抱歉,我没有测试这个特定的功能,但我希望它足以为您指明正确的方向。

于 2008-11-17T20:03:36.367 回答
6

只需将以下内容添加到 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>

然后在你的jsp中

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

这将与Pattern.match完全相同

于 2013-10-23T00:50:27.410 回答
5

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

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

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

于 2008-11-17T17:52:47.193 回答
1

对于在我的情况下在 jsp 页面中使用 Pattern.matches 来说,调用 java.util.regex.Pattern.matches(regexString,stringToCompare) 就足够了,因为你不能在 jsp 中导入包

于 2017-10-05T14:54:18.963 回答