我在 123 和 321 之间找到了字符串,并使其加粗。
为此,我使用 Pattern 获取 123 之前的字符串、123 到 321 之间的文本以及 321 之后的文本。
谁能帮我获取 123 到 321 之间的所有字符串。
下面的代码只能帮助我获得 123 和 321 的第一次出现。
Pattern p = Pattern.compile("^.*?(123)");
Matcher m = p.matcher(meredithEditorialSectionSegment);
while (m.find()) {
String desc = m.group();
String segDesc = (desc.substring(0, desc.length() - 3));
segmentDesc.add(new Chunk(segDesc, sectionDescriptionFont));
}
descBold = meredithEditorialSectionSegment.substring(meredithEditorialSectionSegment.indexOf("123") + 3);
descBold = descBold.substring(0, descBold.indexOf("321"));
segmentDesc.add(new Chunk(descBold, sectionDescriptionBoldFont));
Matcher matcher = Pattern.compile("(?<=321).*").matcher(meredithEditorialSectionSegment);
matcher.find();
segmentDesc.add(new Chunk(matcher.group(), sectionDescriptionFont));
这应该可以解决问题。
String str = "Could anyone please help me to get all the"+
" strings between 123 and 321.nMaybe 123 and another 321."+
" Also,123 this must be matched.321nhey!"+
" 312 And 123 this must NOT be matched. ";
Pattern pattern = Pattern.compile("(.*?123)(.*?)(321.*?)",Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
StringBuffer sb= new StringBuffer();
int last=0;
while (matcher.find()) {
System.out.print(matcher.group(1)+"["+matcher.group(2)+"]"+matcher.group(3));
last=matcher.end(3);
}
//the rest of the string
System.out.println(str.substring(last));
笔记:
- 我添加了
DOTALL
标志(以避免换行符问题) - 在您的情况下,您只需要调整
group(2)
字符串
输出:
Could anyone please help me to get all the strings between 123[ and ]321.
Maybe 123[ and another ]321. Also,123[ this must be matched.]321
hey! 312 And 123 this must NOT be matched.