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
Java String.replaceAll regex
提问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.replaceAll
method 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("^.*\\", "");