Java, escaping (using) quotes in a regex

前端 未结 2 2043
悲&欢浪女
悲&欢浪女 2020-12-18 13:12

I\'m trying to use the following regex in Java, that\'s supposed to match any lang=\"2-char-lang-name\":

String lang = \"lang=\\\"\" + L.detectL         


        
2条回答
  •  再見小時候
    2020-12-18 13:48

    Three slashes would be correct (\\ + \" becomes \ + " = \"). (Update: Actually, it turns out that isn't even necessary. A single slash also works, it seems.) The problem is your use of [..]; the [] symbols mean "any of the characters in here" (so [..] just means "any character").

    Drop the [] and you should be getting what you want:

    String ab = "foo=\"bar\" lang=\"AB\"";
    String regex = "lang=\\\"..\\\"";
    String cd = ab.replaceFirst(regex, "lang=\"CD\"");
    System.out.println(cd);
    

    Output:

    foo="bar" lang="CD"
    

提交回复
热议问题