我找到了 123 和 321 之间的字符串,并将其设为粗体。
为此,我使用模式获取123之前的字符串、123和321之间的文本以及321<之后的文本/强>。
Could anyone please help me to get all the strings between 123 and 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.321\nhey!"+
" 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.
关于java - 如何在java中提取特定字符串之间的字符串。使用 itext 添加提取的字符串以使其成为粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19703150/