2

Am trying to extract last three strings i.e. 05,06,07. However my regex is working the other way around which is extracting the first three strings. Can someone please help me rectify my mistake in the code.

Pattern p = Pattern.compile("^((?:[^,]+,){2}(?:[^,]+)).+$");
String line = "CgIn,f,CgIn.util:srv2,1,11.65,42,42,42,42,04,05,06,07";
Matcher m = p.matcher(line);
String result;
if (m.matches()) {
    result = m.group(1);
}
System.out.println(result);

My current output:

CgIn,f,CgIn.util:srv2

Expected output:

05,06,07

1 Answer 1

4

You may fix it as

Pattern p = Pattern.compile("[^,]*(?:,[^,]*){2}$");
String line = "CgIn,f,CgIn.util:srv2,1,11.65,42,42,42,42,04,05,06,07";
Matcher m = p.matcher(line);
String result = "";
if (m.find()) {
    result = m.group(0);
}
System.out.println(result);

See the Java demo

The regex is

[^,]*(?:,[^,]*){2}$

See the regex demo.

Pattern details

  • [^,]* - 0+ chars other than ,
  • (?:,[^,]*){2} - 2 repetitions of
    • , - a comma
    • [^,]* - 0+ chars other than ,
  • $ - end of string.

Note that you should use Matcher#find() with this regex to find a partial match.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.