本文介绍了删除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中的所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:56