简体   繁体   English

异常消息可以包含Java中的正则表达式字符吗?

[英]Can an exception message contain regular expression characters in Java?

I'm throwing a new exception in a Java class with some characters that usually get used for regular expressions. 我在Java类中抛出了一个新异常,其中包含一些通常用于正则表达式的字符。

 throw new Exception("(): Fake timeout for message(.*XYZV.* fakeApp .*).");

Is this Ok? 这个可以吗? Or do I need to escape them? 还是我需要逃脱?

You need to escape special regex characters only in places where your string is treated like a regular expression. 仅在将字符串视为正则表达式的地方才需要转义特殊的正则表达式字符。 For example, replaceAll treats its first parameter like a regex, so you would need to escape metacharacters that you want to be interpreted like plain characters. 例如, replaceAll将其第一个参数视为正则表达式,因此您需要转义要像普通字符一样解释的元字符。

Generally speaking, there is no such interpretation in the message passed to the constructor of the Exception class, so there is no need to escape such characters. 一般来说,传递给Exception类的构造函数的消息中没有这种解释,因此不需要转义此类字符。

However, you may have a custom tool for log analysis, which might be interpreting parts of messages as regular expressions. 但是,您可能具有用于日志分析的自定义工具,该工具可能会将消息的某些部分解释为正则表达式。 In this case the answer depends on what you do with the custom tool, because by the time the interpretation of the message as a regex (or anything else for that matter) is happening, Java libraries are completely out of the loop. 在这种情况下,答案取决于您对自定义工具的处理方式,因为在将消息解释为正则表达式(或其他任何与此有关的事情)的时候,Java库已完全退出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM