java - 如何在java中提取特定字符串之间的字符串。使用 itext 添加提取的字符串以使其成为粗体

标签 java string pattern-matching itext string-matching

我找到了 123321 之间的字符串,并将其设为粗体。

为此,我使用模式获取123之前的字符串、123321之间的文本以及321<之后的文本/强>。

Could anyone please help me to get all the strings between 123 and 321.

下面的代码只帮助我得到第一次出现的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));

最佳答案

这应该可以解决问题。

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/

相关文章:

java - 合并排序列表java

javascript - 计算数组中出现次数并获取最高值的简单方法(词袋)

C++:检查字符串是否是有效的 MD5 十六进制哈希

c++ - 从字符串中读取所有整数 C++

performance - Erlang : match on two different lines, 和元组匹配哪个效率更高?

java - 带复选框的 fragment 中的 NullPointEreException

java - 获取标签和值? XML

java - onCreate中出现NullPointerException,调试后似乎找不到原因

pattern-matching - 相似但不同的匹配子句

parsing - 在F#中模拟Prolog回溯