regexp以匹配Java包名称 [英] regexp to match java package name
问题描述
我想检查在stdin中传递的参数是否符合有效的Java程序包名称.我有的正则表达式无法正常工作.在com.example.package中传递以下代码后,我收到了错误消息.我不确定我的正则表达式有什么问题吗?
I want to check if arguments passed in stdin to see if they conform to a valid java package name. The regex I have is not working properly. With the following code passing in com.example.package I receive the error message. I'm not sure what is wrong with my regex?
regex="/^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+[0-9a-z_]$/i"
17 if ! [[ $1 =~ $regex ]]; then
18 >&2 echo "ERROR: invalid package name arg 1: $1"
19 exit 2
20 fi
推荐答案
您非常接近正确的解决方案.只需稍微调整一下正则表达式(也可以考虑@fede的简单正则表达式),然后为不区分大小写的匹配设置 nocasematch
选项.例如:
You are pretty close to the correct solution. Just tweak the regex a bit (also consider @fede's simpler regex) and set the nocasematch
option for case insensitive matching. For example:
regex='^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+[0-9a-z_]$'
shopt -s nocasematch
if ! [[ $1 =~ $regex ]]; then
exit 2
fi
shopt -u nocasematch
您可能会被使用/regex/i
(javascript)或 qr/regex/i
(perl)定义不区分大小写的正则表达式的其他语言误导对象.
You are probably being misled by other languages that use /regex/i
(javascript) or qr/regex/i
(perl) for defining a case-insensitive regex object.
顺便说一句,使用 grep -qi
是另一种更可移植的解决方案.干杯.
Btw, Using grep -qi
is another, more portable, solution. Cheers.
这篇关于regexp以匹配Java包名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!