// Check to make sure value is non-null and matches CSS grammar
// A property may contain more than one class name so we need to
// check each potential class name in the string.
for (Map.Entry<String, String> entry : chromeCssProps.entrySet()) {
String property = entry.getValue();
if (property == null) {
property = "";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Property was null: " + entry.getKey());
}
} else {
String[] classNames = property.split("\\s+");
for (String s : classNames) {
if (!s.matches("-?[_a-zA-Z]+[_a-zA-Z0-9-]*")) {
property = property.replace(s, "");
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Invalid CSS class name in "
+ entry.getKey() + ": "
+ s);
}
}
}
}
entry.setValue(property);
}
Refactorings
No refactoring yet !
MetroidFan2002
July 31, 2010, July 31, 2010 18:45, permalink
The code seems incorrect - as Strings are immutable in Java, the following line should replace line 14: property = property.replace(s, "");
Also, if you prevented nulls from being valid values in the map, you could shorten the method slightly - I'm assuming your regex is working, and everything else is ok.
for (Map.Entry<String, String> entry : chromeCssProps.entrySet()) {
String property = entry.getValue();
String[] classNames = property.split("\\s+");
for (String s : classNames) {
if (!s.matches("-?[_a-zA-Z]+[_a-zA-Z0-9-]*")) {
property = property.replace(s, "");
}
}
entry.setValue(property);
}
Stefan Vartolomeev
August 29, 2010, August 29, 2010 16:54, permalink
Your code for matching (Line 15: !s.matches("-?[_a-zA-Z]+[_a-zA-Z0-9-]*") ) is lot's more readable, but you can gain some performance if you compile your regular expression only once. It is similar to using StringBuilder.append instead of String concatenations.
Pattern classPattern = Pattern.compile("-?[_a-zA-Z]+[_a-zA-Z0-9-]*");
for (Map.Entry<String, String> entry : chromeCssProps.entrySet()) {
String property = entry.getValue();
if (property == null) {
property = "";
debug("Property was null: " + entry.getKey());
} else {
String[] classNames = property.split("\\s+");
for (String s : classNames) {
if (!classPattern.matcher(s).matches()) {
property = property.replace(s, "");
info("Invalid CSS class name in " + entry.getKey() + ": " + s);
}
}
}
entry.setValue(property);
}
I have a map of strings where the values are strings that may contain one or more CSS class names separated by spaces. I want to make sure that each of the class names is valid. If a class is found to be invalid it will be replaced with nothing.