[英]Java regex for replacing all special characters except underscore
I would like a regular expression for removing all special characters except an underscore. 我想要一个正则表达式来删除除下划线之外的所有特殊字符。 I can replace all special characters, but I don't know how to keep the underscores. 我可以替换所有特殊字符,但我不知道如何保留下划线。 Here's the code for removing all speial characters, 这是删除所有特殊字符的代码,
String myname= "!john_smith@#-".replaceAll("\\p{Punct}+", "");
Any ideas how to modify the regex so that I keep underscores? 任何想法如何修改正则表达式,以便我保持下划线?
Thanks, Patrick 谢谢,帕特里克
Well \\\\p...
is the same as [^\\\\P...]
(negated character class of characters not having the property), and then you could put the underscore in there as well: 好吧\\\\p...
与[^\\\\P...]
( 没有属性的字符的否定字符类)相同,然后你也可以将下划线放在那里:
"[^\\P{Punct}_]+"
Alternatively, use a negative lookahead 或者,使用否定前瞻
"(?:(?!_)\\p{Punct})+"
Also, seeing your example, maybe something as simple as this will be enough for you: 另外,看到你的例子,也许这样简单的东西对你来说已经足够了:
"[^\\w\\s]+"
Will remove everything except for letters, digits, underscores and whitespace. 将删除除字母,数字,下划线和空格之外的所有内容。
Use set difference: 使用设定差异:
System.out.println("#%a#%^$^_#$%b#$".replaceAll("[\\p{Punct}&&[^_]]", ""));
prints 版画
a_b
Reference: Character Classes 参考: 字符类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.