tags:

views:

63

answers:

3

I'm using spring for setting my regular expression

spring:

<property name="regularExpressionAsString" value="(?&lt;!\\.TMP)\\Z" />

code:

public void setRegularExpressionAsString(String regularEx) {
    this.regularExpression = Pattern.compile(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?

+3  A: 

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="(?&lt;!\.TMP)\Z" />

bean:

public void setRegularExpression(Pattern regularExpression) {
    this.regularExpression = regularExpression;
}
jjungnickel
That looks much better.
BalusC
I'll check it out
Stijn Vanpoucke
A: 

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.

Noel M
thanks never thought about that
Stijn Vanpoucke
+1  A: 

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="(?&lt;!\\.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="(?&lt;!\.TMP)\Z" />
Stephen C
thx you're absolutly right Stephen !
Stijn Vanpoucke