sattu sattu - 2 months ago 7
Java Question

Regex to match version number for zero or more time

I am writing a regex to match for following type of strings:

my-jar-1.2.3.5.jar
my-jar.jar
my-jar-1.2.jar


With the help of
A regex for version number parsing
I figured out following

String pat = "^my-jar(-|\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+).jar$";
Pattern patt = Pattern.compile(pat);
System.out.println("For my-jar-1.2.jar - " + patt.matcher("my-jar-1.2.jar").find());
System.out.println("For my-jar-1.2.3.5.jar - " + patt.matcher("my-jar-1.2.3.5.jar").find());
System.out.println("For my-jar.jar - " + patt.matcher("my-jar.jar").find());


Output is

For my-jar-1.2.jar - true
For my-jar-1.2.3.5.jar - true
For my-jar.jar - false


How do I include the last case in my regex?

Answer

Would there be anything wrong with the following regex:

^my-jar(\-\d+|\-\d+(\.\d+)*)?\.jar$

Demo here:

Regex101

Comments