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
util. regex Description. Classes for matching character sequences against patterns specified by regular expressions. An instance of the Pattern class represents a regular expression that is specified in string form in a syntax similar to that used by Perl.
Difference between matches() and find() in Java RegexThe matches() method returns true If the regular expression matches the whole text. If not, the matches() method returns false. Whereas find() search for the occurrence of the regular expression passes to Pattern.
The java.util.regex package provides following classes and interfaces for regular expressions.
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
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.
Btw, Using grep -qi
is another, more portable, solution. Cheers.
You could use a simpler regex like this:
(?:^\w+|\w+\.\w+)+$
Working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With