如何在java中提取特定字符串之间的字符串。使用itext添加提取的字符串使其变为粗体
我正在查找介于123和321之间的字符串,并将其设置为粗体 为此,我使用该模式获取123之前的字符串、123和321之间的文本以及321之后的文本 谁能帮我找到123和321之间的所有字符串 下面的代码仅帮助我获取第一次出现的123和321如何在java中提取特定字符串之间的字符串。使用itext添加提取的字符串使其变为粗体,java,string,pattern-matching,itext,string-matching,Java,String,Pattern Matching,Itext,String Matching,我正在查找介于123和321之间的字符串,并将其设置为粗体 为此,我使用该模式获取123之前的字符串、123和321之间的文本以及321之后的文本 谁能帮我找到123和321之间的所有字符串 下面的代码仅帮助我获取第一次出现的123和321 Pattern p = Pattern.compile("^.*?(123)"); Matcher m = p.matcher(meredithEditorialSectionSegment); while (m.find()) { String des
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));
Pattern p=Pattern.compile(“^.*(123)”;
匹配器m=p.Matcher(MereditHeditionalSectionSegment);
while(m.find()){
字符串desc=m.group();
字符串segDesc=(desc.substring(0,desc.length()-3));
添加(新块(segDesc,sectionDescriptionFont));
}
descBold=MereditHeditionalSectionSegment.substring(MereditHeditionalSectionSegment.indexOf(“123”)+3);
descBold=descBold.substring(0,descBold.indexOf(“321”);
segmentDesc.add(新块(descBold,sectionDescriptionBoldFont));
Matcher Matcher=Pattern.compile((?这应该可以做到)
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
标志(用于避免换行问题)
- 在您的情况下,您只需调整
组(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.
请注意,如果同步不是一个问题,您可能应该使用StringBuilder
来代替。从StringBuffer javadoc:到JDK 5发行版,这个类已经补充了一个为单线程使用而设计的等效类StringBuilder。StringBuilder类通常应该优先于这个类使用,因为它支持所有相同的操作,但速度更快,因为它不执行同步。
@ABoschman这是真的,但这只是一个例子。如果你再看一遍这个问题,其中没有字符串连接。无论如何,你是对的,你是对的,它与这个问题并不相关,但我们不妨设置一个正确的例子。:)@看一看,我不知道