DroidOS
DroidOS

Reputation: 8910

Misbehaving Regex

I have been using the RegEx /[ -~]/i in JavaScript for a while now and found that it works well testing for any ASCII character including the space. Today I accidentally used /^[ -~]$/i and found much to my surprise that /^[ -~]$/i.test('Stackoverflow is great') failed owing to the space character. My understanding of Regexes is rather limited but even so I fail to see what I might be doing wrong here. Perhaps somone here can shed some light on what is happening?

Upvotes: 2

Views: 43

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You miss a quantifier, a + or *:

alert(/^[ -~]*$/i.test('Stackoverflow is great'));

Without the quantifier a character class just matches 1 symbol. You need that quantifier in this case because you added anchors that require matching at the beginning of the string (^) and at the string end ($).

Note that * means match 0 or more occurrences of the preceding subpattern, and + matches 1 or more occurrences.

And it is true as for what your regex matches as the hyphen creates a range between a space and a tilde:

enter image description here

Upvotes: 4

Related Questions