简体   繁体   中英

Scala: matching special characters

In Scala I need to test if a string has any of the following 'special' characters: !@#\\$^%&*()_-\\+={}[]|;:"'<,>.?/

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("""~`!@#\$^%&*()_-\+={}[]|;:"'<,>.?/""")

results in exception:

 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)

Any ideas?

You need to put all the special characters into character class.

[~!@#$^%&*\\(\\)_+={}\\[\\]|;:\"'<,>.?`/\\\\-]

If you want to add space also, then it should be

[~!@#$^%&*\\(\\)_+={}\\[\\]|;:\"'<,>.?` /\\\\-]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM