Search code examples
javaregexjtextareareplaceall

How to Perform Regular Expression in JTextArea of Swing


I want to Replace all Matched words with given Regular Expression.I wrote code for that.But,It just replace it but that particular action was not performed.When I select the Regular Expression then I click on Replace All,It will replace with particular action,not replace with the given String/Character. For example My input is "\n",Matched String/Character replace with New line Action,not replace new Line Character.Please check it and help me.Thank you. My Code:

public class RegularExp extends javax.swing.JFrame {
JTextArea text;
int i=0;
UndoManager undoManager = new UndoManager();
public RegularExp() {
    initComponents();
    text = new JTextArea();
    replace.setEnabled(false);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    tp = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    fileMenu = new javax.swing.JMenu();
    open = new javax.swing.JMenuItem();
    replace = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    fileMenu.setText("File");

    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });
    fileMenu.add(open);

    replace.setText("Replace");
    replace.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            replaceActionPerformed(evt);
        }
    });
    fileMenu.add(replace);

    jMenuBar1.add(fileMenu);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void replaceActionPerformed(java.awt.event.ActionEvent evt) {                                        
    JDialog replace_dialog=new JDialog(RegularExp.this);
    replace_dialog.setTitle("Replace");
    JLabel find_label=new JLabel("Find what");
    final JTextField find_tf=new JTextField(10);
    JLabel replace_label=new JLabel("Replace With");
    final JTextField replace_tf=new JTextField(10);
    final JCheckBox regx=new JCheckBox("Regular Expression");
    JButton replaceAll=new JButton("Replace All");
    replace_dialog.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(5, 5, 5, 5);
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.WEST;
    replace_dialog.add(find_label, c);
    c.gridx++;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;
    replace_dialog.add(find_tf, c);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 2;
    replace_dialog.add(replace_label, c);
    c.gridx++;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;
    replace_dialog.add(replace_tf, c);
    c.gridx++;
    c.gridx++;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    replace_dialog.add(replaceAll, c);
    c.gridx=0;
    c.gridy++;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    replace_dialog.add(regx, c);
    replace_dialog.setSize(400,400);
    replace_dialog.setLocationRelativeTo(null);
    replace_dialog.pack();
    replace_dialog.setVisible(true);
    replaceAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(regx.isSelected()){
                int caret_pos=text.getCaretPosition();
                text.setText(text.getText().replaceAll(find_tf.getText(),"\\"+ replace_tf.getText()));
                text.setCaretPosition(caret_pos);
            }    
            else {
                int caret_pos=text.getCaretPosition();
                text.setText(text.getText().replaceAll(find_tf.getText(), replace_tf.getText()));
                text.setCaretPosition(caret_pos);
            }
        }
    });
}                                       

private void openActionPerformed(java.awt.event.ActionEvent evt) {                                     
    final JFileChooser jc = new JFileChooser();
    int returnVal=  jc.showOpenDialog(RegularExp.this);
    String title;
    File file=null;
    if(returnVal == JFileChooser.APPROVE_OPTION)
    file = jc.getSelectedFile();
    if (jc.getSelectedFile()!= null) {
        BufferedReader br = null;
        StringBuffer str = new StringBuffer("");
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                str.append(line + "\n");
            }
        }
        catch (IOException ex) {
            Logger.getLogger(RegularExp.class.getName()).log(Level.SEVERE, null, ex);
        }
        String t = str.toString();
        final JInternalFrame internalFrame = new JInternalFrame("",true,true);
        title=file.getName();
        text.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
        internalFrame.add(text);
        i+=1;
        internalFrame.setName("Doc "+i);
        JScrollPane scrollpane=new JScrollPane(text);
        internalFrame.setTitle(title);
        tp.add(internalFrame);
        internalFrame.add(scrollpane);
        internalFrame.setVisible(true);
        text.setText(t);
        text.setCaretPosition(0);
        replace.setEnabled(true);
    }
}                                    

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(RegularExp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(RegularExp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(RegularExp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(RegularExp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new RegularExp().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem replace;
private javax.swing.JTabbedPane tp;
// End of variables declaration                   
}

Solution

  • The point is: in one of the cases you should use the function replace() instead of replaceAll().

    Note that both replace() and replaceAll() functions replaces all the occurrences. The only difference between them is that replaceAll() uses regex, while replace() don't.

    So you should use the following code:

    replaceAll.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            int caret_pos = text.getCaretPosition();
            if(regx.isSelected()){
                text.setText(text.getText().replaceAll(
                        find_tf.getText(), replace_tf.getText()));
            }
            else{
                text.setText(text.getText().replace(
                        find_tf.getText(), replace_tf.getText()));
            }
            text.setCaretPosition(Math.min(caret_pos,text.getText().length()));
        }
    });
    

    According to your comments, your question does not have to do with regular expressions. You simply want to handle special characters like \n and \t differently in two situations. I'll let the above explanation to the ones that really want to use regular expression. Also, I'll add below, the answer to your specific situation.

    UPDATED ANSWER TO WORK IN BOTH SCENARIOS THAT YOU'VE DESCRIBED IN COMMENTS:

    replaceAll.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            int caret_pos = text.getCaretPosition();
            if(regx.isSelected()){
                text.setText(text.getText().replace(
                        find_tf.getText().replace("\\n","\n").replace("\\t","\t"),
                        replace_tf.getText().replace("\\n","\n").replace("\\t","\t")));
            }
            else{
                text.setText(text.getText().replace(
                        find_tf.getText(),
                        replace_tf.getText()));
            }
            text.setCaretPosition(Math.min(caret_pos,text.getText().length()));
        }
    });
    

    This code deals with \n and \t. If you want to deal with other special characters you just have to add other replaces. For example: if you want to deal with \r you need the following code:

    text.setText(text.getText().replace(
            find_tf.getText().replace("\\n","\n").replace("\\t","\t").replace("\\r","\r"),
            replace_tf.getText().replace("\\n","\n").replace("\\t","\t").replace("\\r","\r")));
    

    You can have a list of all JAVA escape sequences here: http://docs.oracle.com/javase/tutorial/java/data/characters.html

    • \t Insert a tab in the text at this point.
    • \b Insert a backspace in the text at this point.
    • \n Insert a newline in the text at this point.
    • \r Insert a carriage return in the text at this point.
    • \f Insert a formfeed in the text at this point.
    • \' Insert a single quote character in the text at this point.
    • \" Insert a double quote character in the text at this point.
    • \\ Insert a backslash character in the text at this point.