2

我在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));
4

1 回答 1

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. 
于 2014-05-05T11:40:38.807 回答