Java Regex - Not coloring all matching word in JTe

2019-09-02 06:40发布

问题:

I want coloring all word that matching with commment

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

but, it some words are not colored at JTextPane which contains many comments

回答1:

Your code retrieve the comment text (getkomen=komen.group()), then searches for the first instance of that text (...indexOf(getkomen)). If you have multiple identical comments, only the first one will be colored.

The Matcher will give you the position of the found text using start() and end(). You should just use those.

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


回答2:

You can change from source.select(start, start+getkomen.length) to 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);
    }
}