2

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?

Community
  • 1
  • 1
sattu
  • 632
  • 1
  • 22
  • 37

4 Answers4

5

Would there be anything wrong with the following regex:

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

Demo here:

Regex101

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

This should work for you :

public static void main(String[] args) {
    String s1 = "my-jar-1.2.3.5.jar";
    String s2 = "my-jar.jar";
    String s3 = "my-jar-1.2.jar";

    System.out.println(s1.matches("my-jar(?:\\.|\\-(\\d+.)+)jar"));
    System.out.println(s2.matches("my-jar(?:\\.|\\-(\\d+.)+)jar"));
    System.out.println(s3.matches("my-jar(?:\\.|\\-(\\d+.)+)jar"));
}

O/P :

true true true

"my-jar(?:\\.|\\-(\\d+.)+)jar" ==> Starts with my-jar followed by either a "." or a - and one or more sets of <digit>. and then `jar.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

Can you try this

^my-jar(-|\\.)?(?:(\\d*)\\.)?(?:(\\d*)\\.)?(?:(\\d*)\\.)?(\\*|\\d*).jar$
mhasan
  • 3,703
  • 1
  • 18
  • 37
1

Try

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

It matches the mandatory filename, my-jar, and then has an optional non-capturing group, which is matched if an hyphen followed by digits comes next. Then, still inside the first optional group, there's another non capturing group that can be repeated any number of time (0-...) with a commencing dot followed by digits.

Finally, whether the optional group has been matched, or not, it ends by matching the .jar sequence.

Check it out at regex101 here.

SamWhan
  • 8,296
  • 1
  • 18
  • 45