ulquiorra ulquiorra - 5 months ago 13
Java Question

extract multiples same string from a string

I need to split a String by a specific

String
which can be placed anywhere (there can be multiple occurences of this string at same time) and reconstruct the entire string by adding extracts into something like a
StringBuffer
. The case of the specific String to seek must be insensitive

For example:

String targeted = "test" ;
String plainString ="azertytestqwerty";

//desired outcome

StringBuffer sb = new StringBuffer();
sb.append("azerty");
sb.append("test");
sb.append("qwerty");

--------------------------

String targeted = "test" ;
String plainString ="a.test";

//desired outcome

StringBuffer sb = new StringBuffer();
sb.append("a.");
sb.append("test");

--------------------------

String targeted = "test" ;
String plainString ="test mlm";

//desired outcome

StringBuffer sb = new StringBuffer();
sb.append("test");
sb.append("mlm");

--------------------------

String targeted = "test" ;
String plainString ="aaatestzzztest";

//desired outcome

StringBuffer sb = new StringBuffer();
sb.append("aaa");
sb.append("test");
sb.append("zzz");
sb.append("test");


Any simple way to do this?

I think I need to use a regex like:

Pattern pattern = Pattern.compile(".*"+targeted +".*");
Matcher matcher = pattern.matcher(text);
if (matcher.find())
{
System.out.println(matcher.group(1));
}


But then I don't know how to extract the strings and add them in same order

The reason why I do this it's because the
plainString
will be added into a Excel cell using POI but I need to add font color for the targeted string.

Example:

XSSFRichTextString richString = new XSSFRichTextString();
richString.append("azerty");
richString.append("test", highlightFont);
richString.append("qwerty");
cell.setCellValue(richString);


Thank you very much

Answer

Here is the method, you can try any combination.

public String extractMultiples(String plainString, String targeted) {
    StringBuffer sb = new StringBuffer();

    // split covers all occurrences in the beginning;empty element, and in
    // the middle
    String[] result = plainString.split(targeted);
    for (int i = 0; i < result.length; i++) {
        sb.append(result[i]);
        if (i < result.length - 1)// not the last one
            sb.append(targeted);
    }

    // in the end
    if (plainString.endsWith(targeted))
        sb.append(targeted);
    return sb.toString();
}