Python regex for Java package names

I'm having trouble figuring out valid Java package names using Python. Here is the code:

    packageName = "com.domain.lala" # valid, not rejected -> correct
    #packageName = ".com.domain.lala" # invalid, rejected -> correct
    #packageName = "com..domain.lala" # invalid, not rejected -> incorrect
    #packageName = "com.domain.lala." # invalid, not rejected -> incorrect

    matchObject = re.match("([a-z_]{1}[a-z0-9_]*(\.[a-z_]{1}[a-z0-9_]*)*)",
                           packageName)

    if matchObject is not None:
        print packageName + " is a package name!"
    else:
        print packageName + " is *not* a package name!"
        Utilities.show_error("Invalid Package Name", "Invalid package name " + packageName + "!", "Ok", "", "")

Package names must begin with a lowercase letter or underscore, and each dot must be accompanied by at least one lowercase letter or underscore. All other characters can be lowercase, numbers, or underscores. No jogging is allowed and may not end or start from a point.

How to solve this?

+5
source share
5 answers

$ , . , , .

+4

Java. , .

:

^([a-zA-Z_]{1}[a-zA-Z0-9_]*(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*)?$
+3

You need to put the beginning of line markers and the end of line. Therefore, the regex should look like this:

^([a-z_]{1}[a-z0-9_]*(\.[a-z_]{1}[a-z0-9_]*)*)$
+2
source

The following model worked well for me:

/^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+[0-9a-z_]$/i;

Results can be found in this gist .

[โœ”] me.unfollowers.droid
[โœ”] me_.unfollowers.droid
[โœ”] me._unfollowers.droid
[โœ”] me.unfo11llowers.droid
[โœ”] me11.unfollowers.droid
[โœ”] m11e.unfollowers.droid
[โœ—] 1me.unfollowers.droid
[โœ”] me.unfollowers23.droid
[โœ”] me.unfollowers.droid23d
[โœ”] me.unfollowers_.droid
[โœ”] me.unfollowers._droid
[โœ”] me.unfollowers_._droid
[โœ”] me.unfollowers.droid_
[โœ”] me.unfollowers.droid32
[โœ—] me.unfollowers.droid/
[โœ—] me:.unfollowers.droid
[โœ—] :me.unfollowers.droid
[โœ—] me.unfollowers.dro;id
[โœ—] me.unfollowe^rs.droid
[โœ—] me.unfollowers.droid.
[โœ—] me.unfollowers..droid
[โœ—] me.unfollowers.droid._
[โœ”] me.unfollowers.11212
[โœ”] me.1.unfollowers.11212
[โœ—] me..unfollowers.11212
[โœ—] abc
[โœ—] abc.
[โœ—] .abc
+2
source

Instead, you can parse a string:

def valid_java_package_name(string):
    tree = string.split('.')

    if len(tree) == 0:
        return false

    for node in tree:
        if not valid_java_package_node(node):
            return false

    return true
0
source

All Articles