Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid text highlighting of a string in a line starting with a specific symbol [java]

I'm making a text editor which finds a string in the first line of a text and highlights it and its occurrences throughout the text. The problem is that it also highlights the occurrences located in the comment lines (started with "#"). This is my code so far:

    import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class TextArea {

    public static void main(String[] args) {
        JFrame frame = new JFrame("textArea");
        frame.setSize(500,500);

        final JTextArea textArea = new JTextArea() ;
        frame.add(textArea);

        frame.setVisible(true);

        textArea.getDocument().addDocumentListener(new DocumentListener(){

            @Override
            public void changedUpdate(DocumentEvent e) {
                try {
                    String keyWords = findKeyWord();
                    findOccurrences(keyWords);
                } catch (BadLocationException ex) {
                    Logger.getLogger(TextArea.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                try {
                    String keyWords = findKeyWord();
                    findOccurrences(keyWords);
                } catch (BadLocationException ex) {
                    Logger.getLogger(TextArea.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                try {
                    String keyWords = findKeyWord();
                    findOccurrences(keyWords);
                } catch (BadLocationException ex) {
                    Logger.getLogger(TextArea.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            public String findKeyWord() throws BadLocationException {
                String keyWord = ""; 

                for( String line : textArea.getText().split("\n")){
                    if (line.trim().length() > 0) {
                        if( !line.startsWith("#") ){                            
                            int keywordEndPosition = line.indexOf("#");
                            keyWord = line.substring(0, keywordEndPosition == -1 ? line.length() : keywordEndPosition);
                            keyWord = keyWord.trim();
                            break;
                        } 
                    }                       

                }                 
            return keyWord;                
            }

            public void findOccurrences(String keyWords) throws BadLocationException {
                Highlighter highlighter = textArea.getHighlighter();
                DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);
                String[] keyArray;
                highlighter.removeAllHighlights();

                keyArray = keyWords.split("[(,)]");
                for (int i=0; i<keyArray.length; i++) {
                    keyArray[i] = keyArray[i].trim();                }

                for (String keyWord : keyArray) {
                    if (keyWord.isEmpty())
                        return;

                    Pattern pattern = Pattern.compile( Pattern.quote(keyWord) );
                    Matcher matcher = pattern.matcher(textArea.getText());  


                    while(matcher.find()) {
                        highlighter.addHighlight(matcher.start(), matcher.end(), painter);
                    }
                }
            }


        });     
    }   
}

How can I edit this code to avoid highlighting of occurrences situated after a "#" symbol in a line? Thanks for your help!

like image 706
Pino Avatar asked Apr 08 '16 14:04

Pino


1 Answers

Replace the pattern with:

Pattern pattern = Pattern.compile("(?<!#.{0,1000})" + Pattern.quote(keyWord));

i am using a regular expression with negative lookbehind and a length of up to 1000 characters between # and the keyword.

like image 191
tak3shi Avatar answered Sep 30 '22 10:09

tak3shi