删除java中的所有特殊字符 [英] remove all special characters in java

查看:1041
本文介绍了删除java中的所有特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

用空字符串替换所有非字母数字字符





import java.util.Scanner;
import java.util.regex.*;
public class io{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
String c;
if((c=scan.nextLine())!=null)
 {
Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
Matcher match= pt.matcher(c);
    while(match.find()){
         c=c.replace(Character.toString(c.charAt(match.start())),"");
         }
    System.out.println(c);
      }
   }
}

案例1

Input : hjdg$h&jk8^i0ssh6
Expect : hjdghjk8i0ssh6
Output : hjdgh&jk8^issh6

案例2

Input : hjdgh&jk8i0ssh6
Expect : hjdghjk8i0ssh6
Output : hjdghjk8i0ssh6

案例3

Input : hjdgh&j&k8i0ssh6
Expect : hjdghjk8i0ssh6
Output : hjdghjki0ssh6

任何人请帮助我弄清楚,我的代码逻辑有什么问题?

Anyone please help me to figure out, what is wrong in my code logic ??

推荐答案

使用 [\\W +] [^ a-zA-Z0-9]作为正则表达式匹配任何特殊字符,并使用String.replaceAll(regex,String)将spl charecter替换为空字符串。记住,作为String.replaceAll的第一个arg是一个正则表达式,你必须用反斜杠转义它以将em视为文字字符。

use [\\W+] or "[^a-zA-Z0-9]" as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.

          String c= "hjdg$h&jk8^i0ssh6";
        Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
        Matcher match= pt.matcher(c);
        while(match.find())
        {
            String s= match.group();
        c=c.replaceAll("\\"+s, "");
        }
        System.out.println(c);

这篇关于删除java中的所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆