일치하는 모든 단어를 주어진 정규 표현식으로 바꿔야합니다. 코드를 작성했습니다. 다만 바꿀 수는 있지만 특정 동작은 수행되지 않았습니다. 정규 표현식을 선택하면 모두 바꾸기를 클릭하면 특정 동작으로 대체되며 주어진 문자열/문자로 대체되지 않습니다. 예를 들어, 입력 내용이 "\ n"이고, 일치하는 문자열/문자가 줄 바꿈 문자로 바뀝니다. 줄 바꿈 문자를 바꾸지 않습니다. 확인하고 도움하십시오. 감사합니다. 내 코드 :스윙의 JTextArea에서 정규 표현식을 수행하는 방법
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
}
위의 코드 또한 주어진 문자열을 찾기 문자열로 바꿉니다.입력 텍스트는 다음과 같습니다 : SN1 * 84 * 9 * CA ~ HL * 95 * 2 * I ~ HL * 98 * 2 * I ~ CTT * 98, 찾을 내용 : ~ 및 바꾸기 : n.Case 1 : Regular Expression을 선택한 후 Select All Button을 클릭하십시오. 출력은 4 줄이어야합니다. 예제 출력 : SN1 * 84 * 9 * CA HL * 95 * 2 * I HL * 98 * 2 * I CTT * 98 case 2 : 정규 표현식을 선택하지 않고 [모든 버튼 바꾸기]를 클릭하면 출력은 한 줄이어야합니다. 예제 출력은 SN1 * 84 * 9 * CA * nHL * 95 * 2 * I \ nHL * 98 * 2 * I \ nCTT * 98. – user3912886
위의 경우 두 번째 사례가 정상적으로 작동합니다. 첫 번째 사례를 확인하십시오. 답장을 보내 주셔서 감사합니다. – user3912886
나는 당신이 원하는 것을 이제 이해합니다. 위의 답변을 귀하의 필요에 맞게 업데이트했습니다. – viniciussss