Uzma
Uzma

Reputation: 45

how to extract a part of string using regex

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

Upvotes: 2

Views: 50

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626826

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.

Upvotes: 4

Related Questions