Regexp to match java package name

I want to check if arguments are passed to stdin to make sure they match a valid java package name. The regular expression is not working correctly for me. With the following code going through com.example.package I get an error. 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

      

+3


source to share


2 answers


You are pretty close to making the right decision. Just tweak the regex a bit (also consider the simplified regex @fede) and set the parameter nocasematch

to case insensitive. 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

      



You are probably being misled by other languages ​​that use /regex/i

(javascript) or qr/regex/i

(perl) to define a case insensitive regex object.

Btw, use grep -qi

is a different, more portable solution. Greetings.

+4


source


You can use a simpler regex:

(?:^\w+|\w+\.\w+)+$

      



Working demo

+2


source







All Articles