How do I use regular expressions to get a second matcher in Java?

See English answers > match at every second occurrence

VA-123456-124_VRG.tif

I tried this:

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

But I got 123456-124 of the above regular expression in Java

I just need 124

How can I do this?

Solution

I will use a formal pattern matcher here, as specific as possible I will use this mode:

^[^-]+-[^-]+-([^_]+).*

Then check the first capture group for possible matches This is a valid code fragment:

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

By the way, a liner can also work here:

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

However, it should be noted here that it is not very specific and may fail due to your other data

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>