I'm using spring for setting my regular expression
spring:
<property name="regularExpressionAsString" value="(?<!\\.TMP)\\Z" />
code:
public void setRegularExpressionAsString(String regularEx) {
this.regularExpression = Pattern.c开发者_JAVA技巧ompile(regularEx);
}
This doesn't work properly and when I debug my setter I've seen that spring escapes the \ to \\ Is there any way to fix this?
While not answering your original question: Have you considered changing the setter argument to a java.util.regex.Pattern directly? Spring has a PropertyEditor for that, so that you can have your Pattern injected directly:
application-context:
<property name="regularExpression" value="(?<!\.TMP)\Z" />
bean:
public void setRegularExpression(Pattern regularExpression) {
this.regularExpression = regularExpression;
}
I've seen that spring escapes the
\
to\\
Is there any way to fix this?
Actually, I have a feeling that you are the source of those extra backslashes.
<property name="regularExpressionAsString" value="(?<!\\.TMP)\\Z" />
Unless I am misunderstanding your intent, each one of those double backslash characters is supposed to represent a regex escape character. So \\.
is supposed to be a literal full-stop character and \\Z
is supposed to be some character class.
The problem is that you are escaping the regexes as if they were represented as Java string literals in Java source code. But this is XML, so you don't need to escape backslashes at all.
Try changing the above to the following:
<property name="regularExpressionAsString" value="(?<!\.TMP)\Z" />
Have you considered setting the Regex String in a property file? That way, you get the added bonus of being able to change the regex (should you need to) without a full recompile of your application.
You could still set it up in a Spring XML configuration using a PropertyPlaceholderConfigurer
.
精彩评论