我在使用Python确定有效的Java包名称时遇到问题。这是代码:
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", "", "")
包名称必须以小写字母或下划线开头,每个点后面必须至少再跟一个小写字母或下划线。所有其他字符可以是小写字母,数字或下划线。不允许运行任何点,它可能不会以点结束或以点开头。
我该如何解决这个问题?
答案 0 :(得分:4)
在正则表达式的末尾添加$
以强制匹配完整字符串。现在它只匹配一个部分字符串,所以它错误地接受了最后添加了垃圾的有效包名。
答案 1 :(得分:3)
大写字母实际上在Java包名称中是允许的。 他们只是气馁,但它确实有效。
正则表达式应该是:
^([a-zA-Z_]{1}[a-zA-Z0-9_]*(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*)?$
答案 2 :(得分:2)
您需要设置行的开头和行尾标记。所以正则表达式看起来应该像 -
^([a-z_]{1}[a-z0-9_]*(\.[a-z_]{1}[a-z0-9_]*)*)$
答案 3 :(得分:2)
以下模式对我有用:
/^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+[0-9a-z_]$/i;
结果可在此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
答案 4 :(得分:0)
您可以改为解析字符串:
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