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

  • A+
Category:Languages

This question already has an answer here:

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

VA-123456-124_VRG.tif 

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: " + m.group(1) ); }  124 

Demo

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

System.out.println(input.split("[_-]")[2]); 

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

Comment

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