直接上代码吧,因为我对swing也不熟悉,照着API一点点拼出来的。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class RegExpMatcher {
public static void main(String[] args) {
JFrame frame = new JFrame("正则表达式匹配器");
frame.setSize(350, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel queryStringLabel = new JLabel("匹配字符串:");
queryStringLabel.setBounds(10, 20, 80, 25);
JTextField queryStringText = new JTextField(20);
queryStringText.setBounds(100, 20, 165, 25);
JLabel regExpLabel = new JLabel("正则表达式:");
regExpLabel.setBounds(10, 50, 80, 25);
JTextField regExpText = new JTextField(20);
regExpText.setBounds(100, 50, 165, 25);
JButton matchButton = new JButton("部分匹配");
matchButton.setBounds(10, 80, 80, 25);
matchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String queryString = queryStringText.getText().trim();
String regExp = regExpText.getText().trim();
regExp = regExp.replace("\\\\", "\\");
try {
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(queryString);
matchButton.setText("" + matcher.find());
} catch (Exception e2) {
matchButton.setText("error");
throw e2;
}
}
});
JButton matchFullButton = new JButton("完全匹配");
matchFullButton.setBounds(100, 100, 80, 25);
matchFullButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String queryString = queryStringText.getText().trim();
String regExp = regExpText.getText().trim();
regExp = regExp.replace("\\\\", "\\");
try {
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(queryString);
matchFullButton.setText("" + matcher.matches());
} catch (Exception e2) {
matchFullButton.setText("error");
throw e2;
}
}
});
panel.add(queryStringLabel);
panel.add(queryStringText);
panel.add(regExpLabel);
panel.add(regExpText);
panel.add(matchButton);
panel.add(matchFullButton);
frame.add(panel);
frame.setVisible(true);
}
}
打包成可执行的jar包,参考http://www.cnblogs.com/xiaoyucoding/p/7683961.html