29
4

6 に答える 6

43

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.

于 2013-01-31T23:09:10.897 に答える
5

In your character class the )-' is interpreted as a range in the same way as e.g. a-z, it therefore refers to any character with a decimal ASCII code from 41 ) to 96 '.

Since _ has code 95, it is within the range and therefore allowed, as are <, =, > etc.

To avoid this you can either escape the -, i.e. \-, or put the - at either the start or end of the character class:

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

There is no need to escape the ", and note that because you are using the * quantifier, an empty string will also pass the test.

于 2013-01-31T23:26:04.153 に答える
1

Hyphens in character classes denote a range unless they are escaped or at the start or end of the character class. If you want to include hyphens, it's typically a good idea to put them at the front so you don't even have to worry about escaping:

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

By the way, _ does indeed fall between ) and the backtick in ASCII:

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

于 2013-01-31T23:11:42.827 に答える
1

Using this regex you allow all alphanumeric and special characters. Here \w is allowing all digits and \s allowing space

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

The allowed special characters are ! @ # $ & ( ) - ‘ . / + , “ = { } [ ] ? / \ |

于 2020-08-26T14:05:34.073 に答える
0

How about this.. which allows special characters and as well as alpha numeric

"[-~]*$"
于 2017-01-03T16:42:38.440 に答える
0

Because I don't know how many special characters exist, it is difficult to check the string contains special character by white list. It may be more efficient to check the string contains only alphabet or numbers.

for kotlin example

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

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
    }
}
于 2017-12-21T08:05:14.910 に答える