Java String.replaceAll 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/834230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:01:03  来源:igfitidea点击:

Java String.replaceAll regex

javaregexstring

提问by Azder

What is the regex to strip the MY-CORP\ part of na inputed string like MY-CORP\My.Name with the java String.replaceAllmethod so I can get only the My.Name part?

使用 javaString.replaceAll方法去除 MY-CORP\My.Name 等输入字符串的 MY-CORP\ 部分的正则表达式是什么,以便我只能获得 My.Name 部分?

I tried

我试过

public static String stripDomain(String userWithDomain) {
    return userWithDomain.replaceAll("^.*\", "");
}

but i got Unexpected internal error near index 4 ^.*

但我在索引 4 附近遇到了意外的内部错误 ^。*

采纳答案by Michael Borgwardt

Your problem is that the backslash has special meaning both in Java strings and in regexes. So you need four slashes in the Java source code, passing two to the regex parser to get one literal one in the regex:

您的问题是反斜杠在 Java 字符串和正则表达式中都有特殊含义。因此,您需要在 Java 源代码中使用四个斜杠,将两个斜杠传递给正则表达式解析器以在正则表达式中获得一个字面值:

return userWithDomain.replaceAll("^.*\\", "");