extract从字符串中复用相同的字符串

时间:2016-06-14 17:35:37

标签: java string

我需要将一个字符串拆分为一个特定的String,它可以放在任何地方(这个字符串可能同时出现多个),并通过将提取添加到{{1}之类的内容来重构整个字符串}}。要搜索的特定字符串的大小写必须是不敏感的

例如:

StringBuffer

有任何简单的方法吗?

我想我需要使用正则表达式:

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");

但后来我不知道如何提取字符串并按相同的顺序添加它们

我之所以这样做是因为Pattern pattern = Pattern.compile(".*"+targeted +".*"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { System.out.println(matcher.group(1)); } 将使用POI添加到Excel单元格中,但我需要为目标字符串添加字体颜色。

示例:

plainString

非常感谢

2 个答案:

答案 0 :(得分:2)

模式匹配可能有点太多了......

只需对单词进行拆分,然后在结果数组上进行for循环...

实施例

public static void main(String[] args) {
    String targeted = "test";
    String plainString = "azertytestqwerty";
    String[] result = plainString.split(targeted);
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < result.length; i++) {
        sb.append(result[i]);
    }
}

答案 1 :(得分:2)

这是方法,您可以尝试任何组合。

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();
}