Scala:匹配特殊字符 [英] Scala: matching special characters
本文介绍了Scala:匹配特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Scala 中,我需要测试字符串是否具有以下任何特殊"字符:!@#\$^%&*()_-\+={}[]|;:"'<,>.?/
In Scala I need to test if a string has any of the following 'special' characters: !@#\$^%&*()_-\+={}[]|;:"'<,>.?/
我不能简单地使用 'nonword'
"\\W"
正则表达式,因为字符串可能包含正则表达式 "\\W"
也匹配.尝试使用正则表达式:
I can not simply use 'nonword'
"\\W"
regex for this because string may have Cyrillic characters that regex "\\W"
matches as well. Trying to use regex:
new Regex("""~`!@#\$^%&*()_-\+={}[]|;:"'<,>.?/""")
导致异常:
java.util.regex.PatternSyntaxException: Illegal repetition near index 17 ~`!@#\$^%&*()_-\+={}[]|;:"'<,>.?/
^
at java.util.regex.Pattern.error(Pattern.java:1924)
at java.util.regex.Pattern.closure(Pattern.java:3104)
at java.util.regex.Pattern.sequence(Pattern.java:2101)
有什么想法吗?
推荐答案
需要把所有的特殊字符都放到字符类中.
You need to put all the special characters into character class.
[~!@#$^%&*\\(\\)_+={}\\[\\]|;:\"'<,>.?`/\\\\-]
如果你还想添加空间,那么应该是
If you want to add space also, then it should be
[~!@#$^%&*\\(\\)_+={}\\[\\]|;:\"'<,>.?` /\\\\-]
这篇关于Scala:匹配特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文