1

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
  • 161
  • 3
  • 11
  • 6
    `!-@` is a *range* of characters, which includes `<`. In the second example, the position of the `-` means it's just a `-`. Note you can use things like https://regex101.com/ to test your expressions and get explanations of what they match. – jonrsharpe Dec 22 '17 at 09:46
  • Could you brief it...... – Narendra Manam Dec 22 '17 at 09:48
  • Yeah, you're right. Badly worded. I should have said it won't work as you expect it to. Your comment covered it better. – Rory McCrossan Dec 22 '17 at 09:50
  • Closely related: https://stackoverflow.com/questions/5484084/what-literal-characters-should-be-escaped-in-a-regex not sure if dupeworthy though.. – Sebastian Proske Dec 22 '17 at 10:15

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,138
  • 8
  • 24
  • 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