【问题标题】:How to extract string between a particular string in java. Using itext adding extracted string to make it as bold如何在java中的特定字符串之间提取字符串。使用 itext 添加提取的字符串使其变为粗体
【发布时间】:2013-11-11 06:14:33
【问题描述】:

我发现 123321 之间的字符串并将其设为粗体。

为此,我使用 Pattern 获取 123 之前的字符串、123321 之间的文本以及 321。

谁能帮我找出 123321 之间的所有字符串。

下面的代码只能帮助我获得 123321 的第一次出现。

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

【问题讨论】:

    标签: java string pattern-matching itext string-matching


    【解决方案1】:

    这应该可以解决问题。

    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. 
    

    【讨论】:

    • 请注意,如果同步不是问题,您应该改用StringBuilder。来自 StringBuffer javadoc:As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
    • @ABoschman 没错,但这只是一个例子。如果您再次阅读该问题,则其中没有字符串连接。无论如何,你是对的
    • 你说得对,它与问题并不真正相关,但我们不妨树立正确的榜样。 :)
    • @ABoschman 看看stackoverflow.com/questions/47605/…。我不知道
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多