Java 从字符串中删除空格和特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24438714/
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
Remove spaces and special characters from string
提问by Mike
How can I format a string phone number to remove special characters and spaces?
如何格式化字符串电话号码以删除特殊字符和空格?
The number is formatted like this (123) 123 1111
数字格式如下 (123) 123 1111
I am trying to make it look like this: 1231231111
我试图让它看起来像这样:1231231111
So far I have this:
到目前为止,我有这个:
phone = phone.replaceAll("\s","");
phone = phone.replaceAll("(","");
The first line will remove the spaces. Then I am having trouble removing the parentheses. Android studio underlines the "("
and throws the error unclosed group
.
第一行将删除空格。然后我在删除括号时遇到问题。Android studio 下划线"("
并抛出错误unclosed group
。
采纳答案by jcaron
You can remove everything but the digits:
您可以删除除数字以外的所有内容:
phone = phone.replaceAll("[^0-9]","");
回答by M Anouti
You need to escape the (
as it denotes a metacharacter (start of a group) in regular expressions. Same for )
.
您需要转义 ,(
因为它表示正则表达式中的元字符(组的开头)。对)
.
phone = phone.replaceAll("\(","");
回答by Pshemo
To remove all non-digit characters you can use
要删除您可以使用的所有非数字字符
replaceAll("\D+",""); \ \D is negation of \d (where \d represents digit)
If you want to remove only spaces, (
and )
you can define your own character classlike
如果你只想删除空格,(
而且)
你可以定义自己的字符类像
replaceAll("[\s()]+","");
Anyway your problem was caused by fact that some of characters in regex are special. Among them there is (
which can represent for instance start of the group. Similarly )
can represent end of the group.
无论如何,您的问题是由于 regex 中的某些字符是special 引起的。其中有(
哪一个可以代表比如组的开始。同样)
可以代表组的结束。
To make such special characters literals you need to escape them. You can do it many ways
要使这种特殊字符成为文字,您需要对它们进行转义。你可以通过多种方式做到这一点
"\\("
- standard escaping in regex"[(]"
- escaping using character class"\\Q(\\E"
-\Q
and\E
create quote - which means that regex metacharacters in this area should be treated as simple literalsPattern.quote("("))
- this method usesPattern.LITERAL
flag inside regex compiler to point that metacharacters used in regex are simple literals without any special meaning
"\\("
- 正则表达式中的标准转义"[(]"
- 使用字符类转义"\\Q(\\E"
-\Q
并\E
创建引用 - 这意味着该区域中的正则表达式元字符应被视为简单文字Pattern.quote("("))
- 此方法使用Pattern.LITERAL
regex 编译器中的标志来指出 regex 中使用的元字符是简单的文字,没有任何特殊含义
回答by Shadi
public static void main(String[] args){
// TODO code application logic here
String str = "(test)";
String replaced= str.replaceAll("\(", "").replaceAll("\)", "");
System.out.println(replaced);
}