Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match version number for zero or more time

Tags:

java

regex

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?

like image 318
sattu Avatar asked Nov 27 '25 00:11

sattu


1 Answers

Would there be anything wrong with the following regex:

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

Demo here:

Regex101

like image 83
Tim Biegeleisen Avatar answered Nov 29 '25 14:11

Tim Biegeleisen