简体   繁体   English

从字符串中删除空格和特殊字符

[英]Remove spaces and special characters from string

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工作室强调"("并抛出错误unclosed group

您可以删除除数字之外的所有内容:

phone = phone.replaceAll("[^0-9]","");

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 class like 如果你只想删除空格, ()你可以定义自己的角色类

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. 其中有(例如可以表示组的开始。类似地)可以表示组的结束。

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 literals "\\\\Q(\\\\E" - \\Q\\E创建引号 - 这意味着此区域中的正则表达式元字符应视为简单字面值
  • Pattern.quote("(")) - this method uses Pattern.LITERAL flag inside regex compiler to point that metacharacters used in regex are simple literals without any special meaning Pattern.quote("(")) - 此方法在regex编译器中使用Pattern.LITERAL标志指出正则表达式中使用的元字符是简单的文字,没有任何特殊含义

你需要在正则表达式中转义(因为它表示元字符(组的开头)。相同)

phone = phone.replaceAll("\\(","");
public static void main(String[] args){
    // TODO code application logic here
  String str = "(test)";
  String replaced= str.replaceAll("\\(", "").replaceAll("\\)", "");
  System.out.println(replaced);


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM