2014-09-23 94 views
1

在斯卡拉我需要測試一個字符串具有以下任何「特殊」字符:[email protected]#\$^%&*()_-\+={}[]|;:"'<,>.?/斯卡拉:匹配特殊字符

我不能簡單地用'nonword'"\\W"正則表達式是因爲字符串可能有西里爾文字符的正則表達式"\\W"也匹配。嘗試使用正則表達式:

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

結果異常:

java.util.regex.PatternSyntaxException: Illegal repetition near index 17 ~`[email protected]#\$^%&*()_-\+={}[]|;:"'<,>.?/ 
                         ^
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) 

任何想法?

+2

提出的所有字符爲字符類。 '[〜!@#\\ $ ^%&* \\(\\)_ + = \\ {\\} \\ [\\] |;:''<,>。? - ]' – 2014-09-23 11:49:54

+0

謝謝,它適用於所有字符,除了['\ /]如何添加這些? – DarqMoth 2014-09-23 12:19:01

+0

你想添加空格嗎?在下面的答案中,我在字符類中添加了一個正斜槓和反斜槓 – 2014-09-23 12:22:12

回答

4

您需要將所有特殊字符放入字符類中。

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

如果你想添加的空間還,那麼它應該是

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

你需要匹配反斜槓''[ - 〜!@#$ ^%&*()_ + = {} \\ [\\] |;:\「'''<,>。?/ \\ \\]'' – hwnd 2014-09-23 12:25:42

+0

@hwnd:謝謝!這涵蓋了所有這些! – DarqMoth 2014-09-23 12:33:17