How can I get the second matcher in regex in Java?

If you know that's your format, this will return the requested digits.

Everything before the underscore that is not a dash

Pattern pattern = Pattern.compile("([^\-]+)_");

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.


You know you want only digits so be more specific Pattern.compile("-([0-9]+)_");

Tags:

Java

Regex