Regular expression to remove special characters in JSTL tags - regex

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 same text for options value and for displaying but for options value, I need to remove all special characters.
For example if value is Maternal Uncle, then I need
<option value="MaternalUncle">Maternal Uncle</option>
What I am getting is
<option value="Maternal Uncle">Maternal Uncle</option>
There are 2 applications which can use that page and which properties file to load depends on app. If I load values for app 1 then values get displayed properly, Last value in app1 is 'Others' and does not has any special characters. For app 2 it does not trims whitespaces where last value is 'Maternal Uncle'. repOptions in code is ArrayList with values loaded from properties file. Here is my code:
<select name="person" id="person">
<option value="na">Select the relationship</option>
<c:forEach items="${repOptions}" var="repOption">
<option value="${fn:replace(repOption, '[^A-Za-z]','')}">${repOption}</option>
</c:forEach>
</select>
First app removes whitespaces as this value is 4th in list of 9. For app2 , this is last value and regex does not works. If I put Maternal Uncle as first property for app2 then this works fine but requirements is to have it last option.
<option value="${fn:replace(repOption, ' ','')}">
is working for whitespaces but there can be values like Brother/Sister, so I need to remove / also, hence I am using regex.

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

Related

Search for property values within specific HTML tags

Using Visual Studio, within a large ASP.NET project I need to find all images that have a HTML class of "info". These images however can be applied using the following approaches:
Directly in the page, <img alt="..." title="..." class="info" />
As an ASP image, <asp:Image runat="server" ImageUrl="..." CssClass="info" />
As string concatenation, Dim s = "<img .... class=""info"" />" (notice double quotes)
Other hurdles are that images may have multiple classes, e.g. <img ... class="foo info bar" />, so a search for class="info" doesn't work. Also, other HTML elements also use this class, but should be ignored, e.g. <p class="info">Foo</p>.
I need a Regular Expression for searching that provides the following logic:
Must contain img or asp:Image (case-insensitive)
Must contain class or CssClass (case-insensitive)
Must contain info (case-sensitive)
It turns out the problem was the Visual Studio doesn't accept regular expressions that are pasted verbatim.
The test I did worked fine online (see working example)
/(img|asp:Image)(?=.*class\b)(?=.*\binfo\b).*$/igm
However, this failed to find anything in Visual Studio. I didn't realise that I needed to remove the start and end characters. Visual Studio required this revision, which works fine:
(img|asp:Image)(?=.*class\b)(?=.*\binfo\b).*$
Credit to this answer which was a lead in the right direction.

Jmeter Regular Expression Extraction

Could someone help me in getting the value "1237857346" from the following using regex or any other way I could get the value "1237857346" in from HTML in JMeter.
<select class="card_account" name="existing__account">
<option value="" disabled="disabled">Card Number</option>
<option value="1237857346" selected="selected">************4567</option>
</select>
Little bit of background. I am using JMeter and trying to extra the value "1237857346" to pass it in the next request.
It is not very good idea to parse HTML using Regular Expressions as it evidenced by the famous Stack Overflow answer
I would suggest switching to XPath Extractor instead. Add the XPath Extractor as a child of HTTP Request sampler which returns that select and configure it as follows:
XML Parsing Options: tick Use Tidy box. It may not be necessary but if your server response is not XML/XHTML compliant you'll get nothing
Reference Name: anything meaningful, i.e. value - it will be the name of the variable holding extracted data
XPath Expression: //select[#class='card_account']/option[#selected='selected']/#value - it will take
select having class = card_account
option with selected = "selected"
value attribute of the above option
and store it to "value" variable. You will be able to refer to it as ${value} where required.
See following material for further reference:
XPath Tutorial
XPath Language Specification
Using the XPath Extractor in JMeter
You can use the following regex:
<option[^<]*>Card Number</option>\s*<option[^<]*?value="(\d+)"
The value will be in group 1 ($1$), which is exactly what you need.
See demo
In case the are always 12 asterisks (that can be matched with \*{12}) in the <option> node value, you'd can use:
<option[^<]*value="(\d+)"[^<]*>\*{12}\d+</option>
See another demo.

Binding HTML strings in Ember.JS

I am using a third party indexing service (Swiftype) to search through my database. The returned records contains a property called highlight. This simply adds <em> tags around matching strings.
I then bind this highlight property in Ember.JS Handlebars as such:
<p> Title: {{highlight.title}} </p>
Which results in the following output:
Title: Example <em>matching</em> text
The browse actually displays the <em> tags, instead of formatting them. I.e. Handlebars is not identifying the HTML tags, and simply printing them as a string.
Is there a way around this?
Thanks!
Handlebars by default escapes html, to prevent escaping, use triple brackets:
<p> Title: {{{highlight.title}}} </p>
See http://handlebarsjs.com/#html-escaping
Ember escapes html because it could be potentional bad code which can be executed. To avoid that use
Ember.Handlebars.SafeString("<em>MyString</em>");
Here are the docs
http://emberjs.com/guides/templates/writing-helpers/
if you've done that you could use {{hightlight.title}} like wished,...
HTH

actionscript htmltext. removing a table tag from dynamic html text

AS 3.0 / Flash
I am consuming XML which I have no control over.
the XML has HTML in it which i am styling and displaying in a HTML text field.
I want to remove all the html except the links.
Strip all HTML tags except links
is not working for me.
does any one have any tips? regEx?
the following removes tables.
var reTable:RegExp = /<table\s+[^>]*>.*?<\/table>/s;
but now i realize i need to keep content that is the tables and I also need the links.
thanks!!!
cp
Probably shouldn't use regex to parse html, but if you don't care, something simple like this:
find /<table\s+[^>]*>.*?<\/table\s+>/
replace ""
ActionScript has a pretty neat tool for handling XML: E4X. Rather than relying on RegEx, which I find often messes things up with XML, just modify the actual XML tree, and from within AS:
var xml : XML = <page>
<p>Other elements</p>
<table><tr><td>1</td></tr></table>
<p>won't</p>
<div>
<table><tr><td>2</td></tr></table>
</div>
<p>be</p>
<table><tr><td>3</td></tr></table>
<p>removed</p>
<table><tr><td>4</td></tr></table>
</page>;
clearTables (xml);
trace (xml.toXMLString()); // will output everything but the tables
function removeTables (xml : XML ) : void {
xml.replace( "table", "");
for each (var child:XML in xml.elements("*")) clearTables(child);
}

Parse request URL in JSTL

I want to display a specific message based on the URL request on a JSP.
the request URL can be:
/app/cars/{id}
OR
/app/people/{id}
On my messages.properties I've got:
events.action.cars=My car {0} event
events.action.people=My person {1} event
Finally, on my JSP page I want to have the following code:
<spring:message code="events.${element.cause}.${?????}"
arguments="${element.param['0']},${element.param['1']}"/>
I need help figuring out which expression I could use to parse the request URL and obtain the word before the ID.
You can access the request URI in JSTL (actually: EL) as follows:
${pageContext.request.requestURI}
(which thus returns HttpServletRequest#getRequestURI())
Then, to determine it, you'll have to play a bit round with JSTL functions taglib. It offers several string manipulation methods like split(), indexOf(), substringAfter(), etc. No, no one supports regex. Just parse it.
Kickoff example:
<c:set var="pathinfo" value="${fn:split(pageContext.request.requestURI, '/')}" />
<c:set var="id" value="${pathinfo[pathinfo.length - 1]}" />
And use it as ${id}.
/app/(cars|people)/([^/]*)$
will put cars or people in backreference \1, depending on the match, and whatever is left right of the last slash in backreference \2.
My solution so far is to have a RequestUtils class that match the regex ".?/jsp/(\w+)/..jsp" and return the group(1).
in my Jsp I got:
<% request.setAttribute("entity", RequestUtils.getEntityURI(request)); %>
<spring:message code="events.${element.cause}.${entity}"
arguments="${element.param['0']},${element.param['1']}"/>
this of course did the trick. But still it would be better not to have any Java code within the JSP.
If I understand you correctly, I think you need to do something like this:
#RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(#PathVariable String ownerId, Model model) {
model.addAttribute("ownerId", ownerId);
return "myview";
}
As you can see, here the ownerId is read from the URL by Spring MVC. After that, you simply put the variable in the Model map so you can use it in your JSP.