How can I get the the second matcher in regex in Java? [duplicate]

  • A+

This question already has an answer here:

I want to extract the second matcher in a regex pattern between - and _ in this string:


I tried this:

Pattern mpattern = Pattern.compile("-.*?_"); 

But I get 123456-124 for the above regex in Java.

I need only 124.

How can I achieve this?


I would use a formal pattern matcher here, to be a specific as possible. I would use this pattern:


and then check the first capture group for the possible match. Here is a working code snippet:

String input = "A-123456-124_VRG.tif"; String pattern = "^[^-]+-[^-]+-([^_]+).*"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(input);  if (m.find()) {    System.out.println("Found value: " + ); }  124 


By the way, there is a one liner which would also work here:


But, the caveat here is that it is not very specific, and might fail for your other data.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: