PrabaharanKathiresan
PrabaharanKathiresan

Reputation: 1129

RegEx pattern test is failing in javascript

I have below RegEx to validate a string..

var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g;
var res = patt.test(str);

the result will always give true but I thought it would give false.. because I checking any pattern which is not in the patt variable...

The given string is valid and it contains only Alphabets with capital and small case letters. Not sure what is wrong with the pattern.

Upvotes: 0

Views: 136

Answers (2)

GOTO 0
GOTO 0

Reputation: 47951

Note that:

  • A search for a missing pattern is better expressed by a negative condition in code (!patt.test...).
  • You need to escape certain characters like ., (, ), ?, etc. by prefixing them with a backslash (\).

var str = "Thebestthingsinlifearefree";
var patt = /[0-9A-Za-z !\\#$%&\(\)*+,\-\.\/:;<=>\?@\[\]^_`\{|\}~]/;
var res = !patt.test(str);
console.log(res);

This will print false, as expected.

Upvotes: 0

Thomas Ayoub
Thomas Ayoub

Reputation: 29471

Here's your code:

var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g;
console.log(patt.test(str));

The regex

/[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g

will match anything since it accepts match of length 0 due to the quantifier *.

Just add anchors:

var str = "Thebestthingsinlifearefree";
var patt = /^[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*$/;
console.log(patt.test(str));


Here's an explanation or your regex:

[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]* match a single character not present in the list below

    Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    0-9 a single character in the range between 0 and 9
    A-Z a single character in the range between A and Z (case sensitive)
    a-z a single character in the range between a and z (case sensitive)
     ! a single character in the list  ! literally
    \\ matches the character \ literally
    #$%&()*+, a single character in the list #$%&()*+, literally (case sensitive)
    \- matches the character - literally
    . the literal character .
    \/ matches the character / literally
    :;<=>?@ a single character in the list :;<=>?@ literally (case sensitive)
    \[ matches the character [ literally
    \] matches the character ] literally
    ^_`{|}~ a single character in the list ^_`{|}~ literally

Upvotes: 1

Related Questions