6 回答
You need to escape the hyphen:
"^[a-zA-Z0-9!@#$&()\\-`.+,/\"]*$"
If you don't escape it then it means a range of characters, like a-z
.
在您的字符类)-'
中,与 eg 一样,它被解释为一个范围a-z
,因此它指的是具有从 41)
到 96的十进制 ASCII 代码的任何字符'
。
由于_
有代码 95,它在范围内,因此允许,如<
,=
等>
。
为避免这种情况,您可以转义-
, ie \-
,或者将 放在-
字符类的开头或结尾:
/^[a-zA-Z0-9!@#$&()`.+,/"-]*$/
无需转义"
, 并注意因为您使用的是*
量词,所以空字符串也将通过测试。
字符类中的连字符表示一个范围,除非它们被转义或位于字符类的开头或结尾。如果您想包含连字符,通常最好将它们放在前面,这样您甚至不必担心转义:
^[-a-zA-Z0-9!@#$&()`.+,/\"]*$
顺便说一句,_
确实介于)
ASCII 和反引号之间:
http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
使用此正则表达式,您允许所有字母数字和特殊字符。这\w
是允许所有数字并\s
允许空间
[><?@+'`~^%&\*\[\]\{\}.!#|\\\"$';,:;=/\(\),\-\w\s+]*
允许的特殊字符是 ! @ # $ & ( ) - ‘ . / + , “ = { } [ ] ? / \ |
因为不知道有多少特殊字符,所以很难通过白名单来检查字符串是否包含特殊字符。检查字符串仅包含字母或数字可能更有效。
对于科特林示例
fun String.hasOnlyAlphabetOrNumber(): Boolean {
val p = Pattern.compile("[^a-zA-Z0-9]")
return !(p.matcher(this).matches())
}
对于 swift4
func hasOnlyAlphabetOrNumber() -> Bool {
if self.isEmpty { return false }
do {
let pattern = "[^a-zA-Z0-9]"
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
return regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.count)).count == 0
} catch {
return false
}
}
这个怎么样..它允许特殊字符以及字母数字
"[-~]*$"