gpt4 book ai didi

Java - 直接在代码中与属性文件中转义字符

转载 作者:行者123 更新时间:2023-12-01 18:38:43 24 4
gpt4 key购买 nike

如果字符串未转义且值存储在属性文件中,java 编译器是否会自动添加转义字符?

例如,以下语句由于\W 字符而生成编译器错误:

testRegex ="[ \t]*(Not\Wknown)[ \\t]*";

如果我将该字符串存储在属性文件中并按原样加载,编译器不会提示。

应用程序属性

regex.expr = [ \t]*(Not\Wknown)[ \\t]*

MyClass.java

testRegex = System.getProperty("regex.expr");

编译器会自动转义\W 值吗?

最佳答案

读取属性文件时,适用以下规则。这是来自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.

因此,在您站点的示例中,\W 将被视为仅 W。但这与编译器无关。这些规则在运行时应用。

关于Java - 直接在代码中与属性文件中转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20792098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com