Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regexp to match java package name

Tags:

regex

bash

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
like image 222
Whoppa Avatar asked Apr 21 '15 21:04

Whoppa


People also ask

What is regex package in Java?

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.

What is difference between matches () and find () in Java regex?

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.

Which of the following package contains regex class?

The java.util.regex package provides following classes and interfaces for regular expressions.


2 Answers

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.

like image 95
gvalkov Avatar answered Oct 20 '22 03:10

gvalkov


You could use a simpler regex like this:

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

Working demo

like image 37
Federico Piazza Avatar answered Oct 20 '22 03:10

Federico Piazza