Sunday, August 10, 2014

GUI based Regex Matcher [Swing][Java]

This program takes an input string from the user as well as the regular expression to match on the string.
If a match is found it displays the result else displays "Regex pattern incorrect. Try again!" if the regex pattern is incorrect.


Source:

import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;

public class Application extends JFrame {

    JTextArea area1, area2, area3;
    JLabel label1 = new JLabel("Result: "),
            labelTopLeft = new JLabel("Input String"),
            labelTopRight = new JLabel("Regex: ");
    JPanel panel1;
    JScrollPane scroller1, scroller2, scroller3;

    {
        area1 = new JTextArea();
        area2 = new JTextArea();
        area3 = new JTextArea();
        panel1 = new JPanel();
        scroller1 = new JScrollPane(area1);
        scroller2 = new JScrollPane(area2);
        scroller3 = new JScrollPane(area3);
    }

    Ex6() {
        panel1.setLayout(new GridLayout(2, 2));
        panel1.add(labelTopLeft);
        panel1.add(labelTopRight);
        panel1.add(scroller1);
        panel1.add(scroller2);
        add(panel1);

        setLayout(new GridLayout(3, 1));
        add(label1);
        add(scroller3);
        area3.setEditable(false);

        area2.addKeyListener(new FieldListener());

        this.setSize(700, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    class FieldListener extends KeyAdapter {

        public void keyTyped(KeyEvent e) {
            if (e.getKeyChar() == '\n') {
                String userString = area1.getText();
                String userRegex = ((JTextArea) e.getSource()).getText();
                userRegex = userRegex.substring(0, userRegex.length() - 1);
                Pattern p;
                try {
                    p = Pattern.compile(userRegex);
                } catch (Exception ex) {
                    area3.setText("Regex pattern incorrect. Try again!");
                    return;
                }
                Matcher m = p.matcher(userString);
                area3.setText("");
                while (m.find()) {
                    area3.append(m.group() + "\n");
                }
            }
        }
    }

    public static void main(String[] args) {
        Application app = new Application();
    }
}


No comments:

Post a Comment