Does the java compiler automatically add an escape character if a string is not escaped and the value is stored in a properties file?
For example, the following statement generates a compiler error because of the \W character:
testRegex ="[ \t]*(Not\Wknown)[ \\t]*";
If however i store that string in a properties file and load it as it is, the compiler does not complain.
app.properties
regex.expr = [ \t]*(Not\Wknown)[ \\t]*
MyClass.java
testRegex = System.getProperty("regex.expr");
Does the compiler automatically escape the \W value?
When a properties file is read, the following rules apply. This is from the Javadoc for the Properties class
Characters in keys and elements can be represented in escape sequences similar to those used for character and string literals (see sections 3.3 and 3.10.6 of The Java™ Language Specification). The differences from the character escape sequences and Unicode escapes used for characters and strings are:
- Octal escapes are not recognized.
- The character sequence \b does not represent a backspace character.
- The method does not treat a backslash character, \, before a non-valid escape character as an error; the backslash is silently dropped. For example, in a Java string the sequence "\z" would cause a compile time error. In contrast, this method silently drops the backslash. Therefore, this method treats the two character sequence "\b" as equivalent to the single character 'b'.
- Escapes are not necessary for single and double quotes; however, by the rule above, single and double quote characters preceded by a backslash still yield single and double quote characters, respectively.
- Only a single 'u' character is allowed in a Uniocde escape sequence.
So in the example that you site, \W
would be treated as if it were only W
. But this is nothing to do with the compiler. These rules are applied at run time.