RegEx to include alphanumeric and special characters

I have a requirement to allow alphanumeric and some other characters for a field. I use this regex:

 "^[a-zA-Z0-9!@#$&()-`.+,/\"]*$".

Special characters allowed ! @ # $ & ( ) - ‘ . / + , "

But when I test the template with the string "test_for_extended_alphanumeric", the string passes the test. I do not have a template "_". What am I doing wrong?

+5
source share
6 answers

You need to avoid a hyphen:

"^[a-zA-Z0-9!@#$&()\\-`.+,/\"]*$"

If you do not avoid this, it means a range of characters, for example a-z.

+7
source

, . , , , :

^[-a-zA-Z0-9!@#$&()`.+,/\"]*$

, _ ) ASCII:

http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters

0

)-' , , , a-z, ASCII 41 ) 96 '.

_ 95, , <, =, > ..

, -, .. \-, - :

/^[a-zA-Z0-9!@#$&()`.+,/"-]*$/

", , , *, .

0

, .

/\ S ([0-9] [a-zA-Z] [\ sa-zA-Z] [0-9] *) ([A-Za-z0-9! @# $% _ ' ""\^\&. * - \] {1,20}) $/

0

.., , -

"[-~]*$"
0

Since I do not know how many special characters exist, it is difficult to verify that the string contains a special character in the white list. Perhaps checking the string containing only the alphabet or numbers is more efficient.

for example kotlin

fun String.hasOnlyAlphabetOrNumber(): Boolean {
    val p = Pattern.compile("[^a-zA-Z0-9]")
    if (p.matcher(this).matches()) return false
    return true
}

for 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
    }
}
0
source

All Articles