user1703096
user1703096

Reputation: 115

split string for returning only the latter part

I have a string like this:

abc:def,ghi,jkl;mno:pqr,stu;vwx:yza,aaa,bbb;

I want to split first on ; and then on : Finally the output should be only the latter part around : i.e. my output should be

def, ghi, jkl, pqr, stu, yza,aaa,bbb

This can be done using Split twice i.e. once with ; and then with : and then pattern match to find just the right part next to the :. Howvever, is there a better and optimized solution to achieve this?

Upvotes: 3

Views: 385

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213321

So basically you want to fetch the content between ; and :, with : on the left and ; on the right.

You can use this regex: -

"(?<=:)(.*?)(?=;)"

This contains a look-behind for : and a look-ahead for ;. And matches the string preceded by a colon(:) and followed by a semi-colon (;).

Regex Explanation: -

(?<=         // Look behind assertion.
    :        // Check for preceding colon (:)
)            
(            // Capture group 1
    .        // Any character except newline
    *        // repeated 0 or more times
    ?        // Reluctant matching. (Match shortest possible string)
)
(?=          // Look ahead assertion
    ;        // Check for string followed by `semi-colon (;)`
)

Here's the working code: -

   String str = "abc:def,ghi,jkl;mno:pqr,stu;vwx:yza,aaa,bbb;";

   Matcher matcher = Pattern.compile("(?<=:)(.*?)(?=;)").matcher(str);

   StringBuilder builder = new StringBuilder();
   while (matcher.find()) {
       builder.append(matcher.group(1)).append(", ");
   }

   System.out.println(builder.substring(0, builder.lastIndexOf(",")));

OUTPUT: -

def,ghi,jkl, pqr,stu, yza,aaa,bbb

Upvotes: 6

Cory Kendall
Cory Kendall

Reputation: 7314

Don't pattern match unless you have to in Java; if you can't have the ':' character in the field name (abc in your example), you can use indexOf(":") to figure out the "right part".

Upvotes: 0

cl-r
cl-r

Reputation: 1264

String[] tabS="abc:def,ghi,jkl;mno:pqr,stu;vwx:yza,aaa,bbb;".split(";");
StringBuilder sb = new StringBuilder();
Pattern patt = Pattern.compile("(.*:)(.*)");
String sep = ",";
for (String string : tabS) {
    sb.append(patt.matcher(string).replaceAll("$2 ")); // ' ' after $2 == ';' replaced
    sb.append(sep);
}
System.out.println(sb.substring(0,sb.lastIndexOf(sep)));

output

def,ghi,jkl ,pqr,stu ,yza,aaa,bbb 

Upvotes: 3

Related Questions