我需要用特定的String
分割一个字符串,该字符串可以放置在任何地方(该字符串可以同时多次出现),并通过将提取物添加到类似的内容中来重建整个字符串字符串缓冲区。要查找的特定字符串的大小写必须不敏感
例如:
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));
}
但是我不知道如何提取字符串并以相同的顺序添加它们
我这样做的原因是因为 plainString
将使用 POI 添加到 Excel 单元格中,但我需要为目标字符串添加字体颜色。
示例:
XSSFRichTextString richString = new XSSFRichTextString();
richString.append("azerty");
richString.append("test", highlightFont);
richString.append("qwerty");
cell.setCellValue(richString);
非常感谢
最佳答案
这是方法,你可以尝试任意组合。
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();
}
关于java - 从字符串中提取多个相同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818652/