请问为什么 Java 的 String 的 replaceAll 的第一个参数,也就是正则表达式中说『\.』是非法转义符?

2019-02-21 20:09:17 +08:00
 Newyorkcity
http://tool.oschina.net/uploads/apidocs/jquery/regexp.html

. 匹配除“\n ”之外的任何单个字符。要匹配包括“\n ”在内的任何字符,请使用像“(.|\n)”的模式。

. 本身不是一个特殊字符么?我想要得到作为字符的.不应该使用\. 嘛?

不然我应该怎么表达呢?

谢谢
1294 次点击
所在节点    问与答
5 条回复
Newyorkcity
2019-02-21 20:41:17 +08:00
java 官方文档:https://docs.oracle.com/javase/7/docs/api/

Backslashes within string literals in Java source code are interpreted as required by The Java™ Language Specification as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6) It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.

试做翻译:
在.java 文件的代码中的字符串中的 Backslashes (也即\.)会按照 Java™ Language Specification ( java 语言的约定说明)的要求被解释为为 Unicode 或其他字符的转义(这句话我实在是翻译不通),因此在作为正则表达式的字符串中使用两个 Backslashes 来阻止 Backslashes 被 Java bytecode compiler (这是啥东西??)解释为其它东西是有必要的。举个例子,字符串『\b 』作为正则表达式时,匹配的时一个退格符,而『\\b 』匹配一个单词的分界( word boundary 是啥意思??)。字符串『\(hello\)』作为一个正则表达式是非法的并且会导致一个编译时错误,而匹配『(hello)』的正则表达式应该写作『\\(hello\\)』

我的问题倒是在最后一行解决了。。但是整个说明我其实没怎么看懂
Newyorkcity
2019-02-21 20:42:28 +08:00
mxalbert1996
2019-02-21 21:40:14 +08:00
因为你的字符串是先由 Java 编译器来解析而不是直接丢给正则表达式引擎啊,Java 编译器并不知道你这个字符串是正则表达式,所以按照按照普通字符串的方式来解析,那么问题来了,如果你想在一个字符串字面值里加入反斜杠需要怎么写呢?
msg7086
2019-02-22 01:13:18 +08:00
因为你忘了转义反斜线?

要匹配
.
需要用正则
\.
所以需要用正则字符串
"\\."
mezi04
2019-02-22 10:28:13 +08:00
测试好正则式之后再粘贴到编辑器里边,编辑器会自动加上转义字符,那个才是最终形态

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/537388

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX