0

While using regular expression I found one issue. Can any one please give proper reason for the below scenario's

Scenario-1

var regExp=/^[a-zA-Z0-9!-@#$^_:,. ]$/;
regExp.test('<')// True

Scenario-2

var regExp=/^[a-zA-Z0-9-!@#$^_:,. ]$/;
regExp.test('<')// false

There is a change with Exclamation symbol position in regular expression.

Narendra Manam
  • 131
  • 3
  • 10

1 Answers1

0

First Regex

var regExp=/^[a-zA-Z0-9!-@#$^_:,. ]$/;

!-@ matches the range of characters. According to the ASCII values it includes <

Reason

  • a-z - matches a to z characters
  • A-Z - matches A to Z characters
  • 0-9 - matches 0 to 9 characters
  • !-@ matches ! to @ characters
  • #$^_:,. characters will be matched

Second Regex

var regExp=/^[a-zA-Z0-9-!@#$^_:,. ]$/;

- is working as normal - character then this regex doesn't match <

Reason

  • a-z - matches a to z characters
  • A-Z - matches A to Z characters
  • 0-9 - matches 0 to 9 characters
  • -!@#$^_:,. characters will be matched.

Hope you got it

Shalitha Suranga
  • 1,082
  • 8
  • 21
  • 2
    It might be helpful to add *why* it's just a `-` in the second case, and how you could make its position unimportant to avoid the error. – jonrsharpe Dec 22 '17 at 09:53
  • @jonrsharpe updated the answer thanks for advice – Shalitha Suranga Dec 22 '17 at 10:02
  • 2
    I don't think you've answered jonrsharpe's questions. `9-!` doesn't act as a range in the second regex because the `9` is already part of the `0-9` range. (`9-!` wouldn't be a valid range anyway because `!` is before `9` in ASCII order.) Likewise a `-` at the start or end of a character class is literal, for example in `/[-a]/`, `/[a-]/` or even the negative character class `/[^-a]/`. Personally I dislike this feature. I think it comes from regex's origins in Perl. `\-` in a character class will always match a literal `-`, and I prefer to do it that way. – David Knipe Dec 22 '17 at 10:53