I want to use a regular expression in javascript in order to validate a Java package name.
The simplest way to do that is to match a list of words and dots, so I have implemented this regex:
(^(?:[a-z_]+(?:\d*[a-zA-Z_]*)*)(?:\.[a-z_]+(?:\d*[a-zA-Z_]*)*)*$)
This regex ensure the followings:
- the package name can only be formed by letters, digits, dots and underscores.
- the package name must always start with a word (or with an undersccore), but never with a digit or with a dot
- the package name can optionally contain a sequence of a pattern made by: a dot, followed by a word that can start with letters and underscore but not with digits.
- the package name must always end with a non-dot character.
- the package name must start with a lowercase letter by convention (Java permits Uppercase starting package names, even if they are discouraged)
This regex match for example these package names:
com
com.test
com.test.regex
_com._123
comTest.regEx
And it doesnt'match these package names:
123
com.
.com
test.123com
test.123_
This is correct, but it's not enough for my purpose, because if a single word is a Java-reserved word, I have to invalidate the all package name.
Let's take this package name as example:
com.test.package
This package name is recognized as valid with my regex, but the word package
is a Java-reserved word and it can't be used for a Java package name.
Valid package names can be:
com.test.packageTest
com.test.testpackage
The word package
can be a substring of another word, but it can't be a single word between the dots.
How can I modify my regex in order to add the validation of the single words with these rules, avoiding the use of the Java-reserved words?
Thanks