Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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?

like image 353
sAaCh Avatar asked Aug 08 '18 11:08

sAaCh


2 Answers

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("([^\-]+)_");
like image 158
Steven Spungin Avatar answered Sep 18 '22 22:09

Steven Spungin


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.

like image 34
Tim Biegeleisen Avatar answered Sep 19 '22 22:09

Tim Biegeleisen