[ACCEPTED]-Using Regular Expressions in JSP EL-el
While this special case can be handled with 13 the JSTL fn:startsWith
function, regular expressions 12 in general seem like very likely tests. It's 11 unfortunate that JSTL doesn't include a 10 function for these.
On the bright side, it's 9 pretty easy to write an EL function that 8 does what you want. You need the function 7 implementation, and a TLD to let your web 6 application know where to find it. Put these 5 together in a JAR and drop it into your 4 WEB-INF/lib directory.
Here's an outline:
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();
}
}
META-INF/x-c.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>
Sorry, I 3 didn't test this particular function, but 2 I hope it's enough to point you in the right 1 direction.
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 2 in your jsp
<%@taglib uri="http://www.acme.com.au" prefix="custom"%>
custom:matches('aaa.+', someVar) }
This will work exactly the same 1 as Pattern.match
You can use JSTL functions like so -
<c:when test="${fn:startsWith(myVar, 'prefix')}">
Take 1 a look: http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fn/tld-summary.html
for using Pattern.matches inside a jsp page 2 in my case it was enough to call java.util.regex.Pattern.matches(regexString,stringToCompare) because 1 you can't import package in jsp
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.