Java 正则表达式 - 不为 JTextPane 中的所有匹配词着色

Java Regex - Not coloring all matching word in JTextPane

我想给所有与评论匹配的单词着色

public WarnaText(JTextPane source) throws BadLocationException
{
    source.setForeground(Color.BLACK);
    Matcher komen=Pattern.compile("//.+").matcher(source.getText());
    while(komen.find())
    {
        String getkomen=komen.group();
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");

        int start = source.getText().indexOf(getkomen);
        source.select(start,start + getkomen.length());

        source.setCharacterAttributes(aset, false);
    }
}

但是,有些单词在包含许多评论的 JTextPane 中没有着色

您的代码检索评论文本 (getkomen=komen.group()),然后搜索该文本的 第一个 实例 (...indexOf(getkomen))。如果您有多个相同的评论,只有第一个会被着色。

Matcher will give you the position of the found text using start() and end()。你应该只使用那些。

Matcher komen=Pattern.compile("//.+").matcher(source.getText());
while(komen.find())
{
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");

    source.select(komen.start(), komen.end());

    source.setCharacterAttributes(aset, false);
}

您可以从 source.select(start, start+getkomen.length) 更改为 source.select(komen.start(),komen.end())

public WarnaText(JTextPane source) throws BadLocationException
{
    source.setForeground(Color.BLACK);
    Matcher komen=Pattern.compile("(/\*([^\*]|(\*(?!/))+)*+\*+/)|(\/\/.+)").matcher(source.getText());
    while(komen.find())
    {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);

        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");

        source.select(komen.start(),komen.end());

        source.setCharacterAttributes(aset, false);
    }
}