java去掉特殊字符,删除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);

}

}

}

Case 1

Input : hjdg$h&jk8^i0ssh6

Expect : hjdghjk8i0ssh6

Output : hjdgh&jk8^issh6

Case 2

Input : hjdgh&jk8i0ssh6

Expect : hjdghjk8i0ssh6

Output : hjdghjk8i0ssh6

Case 3

Input : hjdgh&j&k8i0ssh6

Expect : hjdghjk8i0ssh6

Output : hjdghjki0ssh6

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

解决方案

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值