开发者

How to set a regex string with spring without it being escaped?

开发者 https://www.devze.com 2023-01-10 22:41 出处:网络
I\'m using spring for setting my regular expression spring: <property name=\"regularExpressionAsString\" value=\"(?&lt;!\\\\.TMP)\\\\Z\" />

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号