java中特殊字符的正则表达式 [英] Regex for special characters in java

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

问题描述

public static final String specialChars1= "\\W\\S";
String str2 = str1.replaceAll(specialChars1, "").replace(" ", "+");

public static final String specialChars2 = "`~!@#$%^&*()_+[]\\;\',./{}|:\"<>?";
String str2 = str1.replaceAll(specialChars2, "").replace(" ", "+");

无论 str1 是什么,我都希望删除除字母和数字以外的所有字符,并用加号 (+) 替换空格.

Whatever str1 is I want all the characters other than letters and numbers to be removed, and spaces to be replaced by a plus sign (+).

我的问题是,如果我使用 specialChar1,它不会删除一些字符,如 ;'",如果我使用 specialChar2 它会给我一个错误:

My problem is if I use specialChar1, it does not remove some characters like ;, ', ", and if I am use specialChar2 it gives me an error :

java.util.regex.PatternSyntaxException: Syntax error U_REGEX_MISSING_CLOSE_BRACKET near index 32:

这是如何实现的?.我已经搜索过,但找不到完美的解决方案.

How can this be to achieved?. I have searched but could not find a perfect solution.

推荐答案

这对我有用:

String result = str.replaceAll("[^\\dA-Za-z ]", "").replaceAll("\\s+", "+");

对于这个输入字符串:

/-+!@#$%^&())";:[]{}\ |wetyk 678dfgh

/-+!@#$%^&())";:[]{}\ |wetyk 678dfgh

结果如下:

+wetyk+678dfgh

+wetyk+678dfgh

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

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