Jill
Jill

Reputation: 539

Testing a string for specific ASCII characters using a regular expression

I'm trying to make sure that a string does not have any weird ASCII characters.

I'm trying to use character classes and negation.

 var tester =/[^\x00-\x001F\x007\x080-\xA1]+/i;

So: no ASCII characters between 00-1F, 07; or 80-A1 should be present. Everything else should be fine.

I am coming back to regular expressions after a long time away... The regular expression is NOT working. I want a string like "hello" to pass and a string like "†ack!" to fail. Or, is my JavaScript/jQuery code wrong?

The code:

var tester2 = /^[^\x00-\x1f\x80-\xa1]+$/;
    $('#testButton').click(function(){
        var text1 = $('#ackInput').val();
        console.log("text: " + text1);
        var allowed  = tester2.test(text1);
        var feedback = "allowed?" + allowed;
        console.log(feedback);
        $('#errorTestInputAllowedChars').text(feedback);
    });

An entry on jsFiddle is at http://jsfiddle.net/jillrenee42/WE79e/2/.

Upvotes: 1

Views: 1824

Answers (3)

maček
maček

Reputation: 77778

Your hex encodings of your desired ranges are incorrect. You want this instead

[^\x00-\x1f\x80-\xa1]

Note I left out \x07 because that's already in the range of \x00-\x1f


EDIT

As Pointy points out, you will need to negate the entire string.

Upvotes: 0

anubhava
anubhava

Reputation: 785156

In Javascript hexcodes are 2 digit codes so following will work for you:

/^[^\x00-\x1F\x07\x80-\xFF]+$/

Javascript Regex Reference

Upvotes: 1

Pointy
Pointy

Reputation: 413717

You need to make sure that the whole string matches:

var tester = /^[^\x00-\x001F\x007\x080-\xA1]+$/i;

That \x notation doesn't seem correct to me, and this works when I try it:

var tester = /^[^\u0000-\u001F\u0080-\u00A1]+$/i;

Upvotes: 1

Related Questions