0

What would be the regular expression to match a correct any-depth JavaScript namespace?

Valid Entries

  • a
  • a.b
  • $a._b.$$c.__d
  • a_$09.b_$09.c_$09

So basically, JavaScript open-name variables joined by dot, and each separate name can contain a-z, A-Z, _, $ and 0-9, but cannot start with 0-9.

Invalid Entries

  • 1a - cannot start with a digit
  • abc.1a - a sub-name cannot start with a digit also
  • .a - cannot have a leading dot
  • a. - cannot end with a dot

I have tried this one: ^([a-z$_][a-z$_0-9]*\.?)*[^\.]$, which while bans the trailing ., allows any extra symbols in the end, such as ,, which is invalid.

6
  • like Regex online? Commented Aug 2, 2018 at 23:39
  • @Sphinx Just tried, it works, though I prefer shorter: /^[a-z][0-9a-z\$\_]*(\.[a-z][0-9a-z\$\_]*)*$/i :) Commented Aug 2, 2018 at 23:42
  • @Sphinx Ops, just found a problem - it doesn't allow leading $ or _, which it should, just like for any open-name JavaScript variable ;) Commented Aug 2, 2018 at 23:44
  • uses [a-zA-Z\_\$] instead of [a-zA-Z] Commented Aug 2, 2018 at 23:45
  • ^[_$a-zA-Z][\w$]*(\.[a-zA-Z][$\w]*)*$ is a simplified version of @Sphinx's regex Commented Aug 2, 2018 at 23:46

1 Answer 1

1

Uses ^[a-zA-Z\$\_][0-9a-zA-Z\$\_]*(\.[a-zA-Z\$\_][0-9a-zA-Z\$\_]*)*$

because \w matches any word character (equal to [a-zA-Z0-9_]),

so as @emsimpson92 said, you can have one simplified version:

^[a-zA-Z\$\_][\$\w]*(\.[a-zA-Z\$\_][\$\w]*)*$

for the shortest version so far as @vitaly-t commented (removed unnecessary escaping), it will be:

/^[a-z$_][$\w]*(\.[a-z$_][$\w]*)*$/i

Regex Online

Sign up to request clarification or add additional context in comments.

3 Comments

I think this one is then the most elegant: /^[a-z\$\_][\$\w]*(\.[a-z\$\_][\$\w]*)*$/i.
Actually, you do a lot of escaping that's not needed. So the ultimate shortest version is: /^[a-z$_][$\w]*(\.[a-z$_][$\w]*)*$/i, if you want to update the answer ;)
@vitaly-t, Hah, thanks for the suggestions. it is my bad habit, add escaping for all special characters...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.