V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Newyorkcity
V2EX  ›  问与答

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

  •  
  •   Newyorkcity · 2019-02-21 20:09:17 +08:00 · 1283 次点击
    这是一个创建于 1862 天前的主题,其中的信息可能已经有所发展或是发生改变。
    http://tool.oschina.net/uploads/apidocs/jquery/regexp.html

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

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

    不然我应该怎么表达呢?

    谢谢
    5 条回复    2019-02-22 10:28:13 +08:00
    Newyorkcity
        1
    Newyorkcity  
    OP
       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
        2
    Newyorkcity  
    OP
       2019-02-21 20:42:28 +08:00
    mxalbert1996
        3
    mxalbert1996  
       2019-02-21 21:40:14 +08:00 via Android   ❤️ 1
    因为你的字符串是先由 Java 编译器来解析而不是直接丢给正则表达式引擎啊,Java 编译器并不知道你这个字符串是正则表达式,所以按照按照普通字符串的方式来解析,那么问题来了,如果你想在一个字符串字面值里加入反斜杠需要怎么写呢?
    msg7086
        4
    msg7086  
       2019-02-22 01:13:18 +08:00   ❤️ 1
    因为你忘了转义反斜线?

    要匹配
    .
    需要用正则
    \.
    所以需要用正则字符串
    "\\."
    mezi04
        5
    mezi04  
       2019-02-22 10:28:13 +08:00
    测试好正则式之后再粘贴到编辑器里边,编辑器会自动加上转义字符,那个才是最终形态
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   956 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:39 · PVG 05:39 · LAX 14:39 · JFK 17:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.