【问题标题】:How to Perform Regular Expression in JTextArea of Swing如何在 Swing 的 JTextArea 中执行正则表达式
【发布时间】:2014-11-01 05:26:18
【问题描述】:

我想用给定的正则表达式替换所有匹配的单词。我为此编写了代码。但是,它只是替换它,但没有执行特定的操作。当我选择正则表达式然后我点击全部替换,它会替换为特定操作,而不是替换为给定的字符串/字符。 例如我的输入是“\n”,匹配的字符串/字符替换为换行操作,而不是替换换行符。请检查并帮助我。谢谢。 我的代码:

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                   
}

【问题讨论】:

    标签: java regex jtextarea replaceall


    【解决方案1】:

    重点是:在其中一种情况下,您应该使用函数replace() 而不是replaceAll()

    请注意,replace()replaceAll() 函数都会替换所有匹配项。它们之间的唯一区别是replaceAll() 使用正则表达式,而replace() 不使用。

    所以你应该使用以下代码:

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

    根据您的 cmets,您的问题与正则表达式无关。您只想在两种情况下以不同的方式处理 \n\t 等特殊字符。我会让上面的解释给那些真正想使用正则表达式的人。另外,我将在下面添加您的具体情况的答案。

    更新的答案适用于您在评论中描述的两种情况:

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

    此代码处理\n\t。如果您想处理其他特殊字符,您只需添加其他替换。例如:如果要处理\r,则需要以下代码:

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

    您可以在此处获得所有 JAVA 转义序列的列表:http://docs.oracle.com/javase/tutorial/java/data/characters.html

    • \t此时在文本中插入一个制表符。
    • \b此时在文本中插入一个退格键。
    • \n此时在文本中插入换行符。
    • \r此时在文本中插入回车。
    • \f 此时在文本中插入换页符。
    • \'此时在文本中插入一个单引号字符。
    • \"此时在文本中插入双引号字符。
    • \\此时在文本中插入一个反斜杠字符。

    【讨论】:

    • 上面的代码也只是将给定的字符串替换为查找字符串。我用一个例子说明我的要求:输入文本为:SN1*84*9*CA~HL*95*2*I~HL *98*2*I~CTT*98 ,查找什么是:~ 并替换为:\n。案例1:当我选择正则表达式时,然后单击全选按钮。输出应为四行。示例输出: SN1*84*9*CA HL*95*2*I HL*98*2*I CTT*98 案例2:当我点击全部替换按钮而不选择正则表达式时,输出应该是一行。示例输出为:SN1*84*9*CA\nHL*95*2*I\nHL*98*2*I\nCTT*98.
    • 在上面第二种情况下工作正常。请检查第一种情况。谢谢您的回复。
    • 我现在明白你想要什么了。我根据您的需求更新了上述答案。
    • 查找内容和替换不是固定的。在上面我只是展示了一个示例。当我将替换为 \t 时,在这种情况下,当 ~ 发生时不添加制表符空间。上面编辑的程序反向不工作 \n 与 ~ 那么输出应该回到原来的。
    • 我的要求是当我选择正则表达式然后单击全选。替换字符串功能也会发生并反转。例如 Find what:~ 和 Replace:\n(~ 替换为新行函数)。查找内容:*和替换:\ t(*替换为制表符空格(四个空格))。反向表示查找内容:\ t替换:*(\ t(制表符空格)替换为*)。它给出原始文本。我想你可以理解我的要求。请检查一次。使用 TextPad 编辑器(搜索->替换)进行参考检查。
    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多