2

Regex is the bane of my existence. I've done plenty tutorials, but the rules never stick, and when I look them up they seem to conflict. Anyways enough of my whining. Could someone tell me why this regex doesn't exclude hyphens or brackets:

/^[A-Za-z_][A-Za-z\d_]*/ 

The way I understand it (or at least what I'm trying to do), the ^ character dictates that the regex should start with the next thing on the list That means the regex should start with [A-Za-z_] or any character a-z and A-Z as well as and underscore _. Then the string can have anything that includes [A-Za-z\d_] which is any alphanumeric character and an underscore. Then I use the * to say that the string can have any number of what was presented previously (any alphanumeric character plus underscore). At no point to I specify a bracket [ or a hyphen -. Why does this expression not exclude these characters

Extra info I'm verifying this with javascript:

function variableName(name) {
    const reg = RegExp("^[A-Za-z_][A-Za-z\d_]*")
    return reg.test(name)
}

function variableName("va[riable0") // returns true should be false
Stephen Agwu
  • 1,013
  • 2
  • 15
  • 29
  • Because your're missing the `$` anchor – Bergi Feb 20 '18 at 21:28
  • just build your regex's in a regex tool like this one: https://www.regexpal.com/ makes it super easy to figure out your regexes without struggling through tutorials. not affiliated, just use it all the time. – Andrew Feb 20 '18 at 21:29
  • 1
    Visualize it: [regexper.com](https://regexper.com/#%2F%5E%5BA-Za-z_%5D%5BA-Za-z%5Cd_%5D*%2F) – epascarello Feb 20 '18 at 21:30
  • Side note: `[A-Za-z\d_]` is represented by `\w`. You can shorten your regex to `^[A-Za-z_]\w*` or `[^\W\d]\w*` – ctwheels Feb 20 '18 at 21:50

2 Answers2

3

It's actually matching the first 2 letters("va"), that's why it's true.

To match the whole phrase, your reg expression should have "$" at the end:

"^[A-Za-z_][A-Za-z\d_]*$"

elyor
  • 998
  • 9
  • 20
2

Your regex matches the part of the string that does not contain the bracket, because your're missing the $ anchor that would (together with ^) force it to match the whole string. Use

const reg = /^[A-Za-z_][A-Za-z\d_]*$/g
//                                 ^
function variableName(name) {
    return reg.test(name)
}

console.log(variableName("va[riable0"))
Bergi
  • 630,263
  • 148
  • 957
  • 1,375