正则表达式测试工具

正则表达式,在软件中的使用已经是家常菜了,主流开发语言都支持.因为它经常使用,也经常需要开发测试新模式,就把早期的这个小工具贴出来,看是不是能给大家带来些方便.

这个小程序大致遵循了MVC的设计思想,明确把M独立出来,这样做是一种必然,因为采用JFC中的JTable来表现数据,所以就要实现一个Model了,本程序命名这个Model为RegexPatternModel,它从XML文件中提取模式数据,因此程序附加有XML处理工具类.为方便程序使用JTable,把它作了一个简单的封装,称为RegexProperty,本类封装了JTable和RegexPatternModel类,还提供了新增和删除操作,编辑可以在JTable上直接进行,最后把这些组件放置到ExtractInfoFrame类实例中进行布局,这里提供了一个菜单保存和退出程序.程序就这么简单.另外这个程序还实施了国际化.下面详细贴出来,并做简单说明 .(因为无法直接下载,否则就不贴出来了).

涉及的类文件:ExtractInfoFrame.java,RegexPatternModel.java,RegexProperty.java,NodeFactory.java,XmlBuilderStatic.java

首先是XML工具类开始.

XmlBuilderStatic

package org.xmlutil;

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import java.io.IOException;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.*;
import java.io.InputStream;
/**
 * 本类提供获得XML入口对象的静态方法.包括Document,XPath,Transformer,DocumentBuilder等.
 */
public class XmlBuilderStatic {
  private static XPath xpath;
  static Transformer transformer;
  private static DocumentBuilder db;
  //private Document doc;
  static {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    xpath = xpathFactory.newXPath();
  }

  public XmlBuilderStatic() {
  }

  private static void init() {
    if (db == null) {
      try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        db = dbf.newDocumentBuilder();
      }
      catch (ParserConfigurationException ex) {
        ex.printStackTrace();
      }
    }
    if (transformer == null) {
      TransformerFactory tf = TransformerFactory.newInstance();
      try {
        transformer = tf.newTransformer();
      }
      catch (TransformerConfigurationException ex1) {
        ex1.printStackTrace();
      }
    }

  }

  public static XPath getXpath() {
    return xpath;
  }

  public static Transformer getTransformer() {
    init();
    return transformer;
  }

  public static DocumentBuilder getDb() {
    init();
    return db;
  }

  public static Document getData(String fn) {
    Document doc = null;
    init();
    try {
      doc = db.parse(fn);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
    catch (SAXException ex) {
      ex.printStackTrace();
    }
    return doc;
  }

  public static Document getDataURL(InputStream is) {
    Document doc = null;
    init();
    try {
      doc = db.parse(is);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
    catch (SAXException ex) {
      ex.printStackTrace();
    }
    return doc;
  }

  public static void main(String[] args) {
  }
}

NodeFactory

package org.xmlutil;

import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;

/**
 * 本类主要提供对于XML节点的各种操作.
 */
public class NodeFactory {
  Document doc;
  static NodeFactory nf;
  static DocumentFragment df;

  public NodeFactory(Document doc) {
    this.doc = doc;
  }

  public NodeFactory() {
  }

  public Node getEleNode(Node node, String elename) {
    Node tnode = doc.createElement(escapeText(elename));
    node.appendChild(tnode);
    return tnode;
  }

  public Node getEleNode(String elename) {
    Node tnode = doc.createElement(escapeText(elename));
    return tnode;
  }

  public void getTextNode(Node node, String elename, String val) {
    Node tnode = doc.createElement(escapeText(elename));
    Text text = doc.createTextNode(escapeText(val));
    node.appendChild(text);
    node.appendChild(tnode);
  }

  public Node getTextNode(String elename, String val) {
    Node node = doc.createElement(escapeText(elename));
    Text text = doc.createTextNode(escapeText(val));
    node.appendChild(text);
    return node;
  }

  public Node getTextNode(String val) {
    Text text = doc.createTextNode(escapeText(val));
    return text;
  }

  public Node getTextNode(Object elename, Object val) {
    return getTextNode(elename.toString(), val.toString());
  }

  public Node getAttrNode(String attrname, String val) {
    Attr attr = doc.createAttribute(escapeText(attrname));
    attr.setNodeValue(escapeText(val));
    return attr;
  }

  public Document getDoc() {
    return doc;
  }

  public void setDoc(Document doc) {
    this.doc = doc;
  }

  public Node getAttrNode(Object attrname, Object val) {
    return getAttrNode(attrname.toString(), val.toString());
  }

  public void getAttrNode(Node node, String attrname, String val) {
    Attr attr = doc.createAttribute(escapeText(attrname));
    attr.setNodeValue(escapeText(val));
    node.getAttributes().setNamedItem(attr);
    //attr.setValue(val);均可以
  }

  private static void initNf() {
    if (nf == null)
      nf = new NodeFactory(XmlBuilder.getInstance().getData());
  }

  public static DocumentFragment getNode(String name, String val) {
    initNf();
    df = XmlBuilder.getInstance().getDocumentFragment();
    df.appendChild(nf.getAttrNode(name, escapeText(val)));
    return df;
  }

  public static DocumentFragment getNode(Object name, Object val) {
    return getNode(name.toString(), escapeText(val.toString()));
  }

  public static Node getNode(Document dd, String name, String val) {
    //df = dd.createDocumentFragment();
    Attr attr = dd.createAttribute(escapeText(name.toString()));
    attr.setNodeValue(escapeText(val.toString()));
    //df.appendChild(attr);
    return attr;
  }

  public static Node getNode(Document dd, Object name, Object val) {
    return getNode(dd, name.toString(), val.toString());
  }


  public static String escapeText(String s) {
    if (s.indexOf('&') != -1 || s.indexOf('<') != -1
        || s.indexOf('>') != -1 || s.indexOf('"') != -1
        || s.indexOf('/'') != -1) {
      StringBuffer result = new StringBuffer(s.length() + 6);
      for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '&') result.append("&amp;");
        else if (c == '<') result.append("&lt;");
        else if (c == '"') result.append("&quot;");
        else if (c == '/'') result.append("&apos;");
        else if (c == '>') result.append("&gt;");
        else result.append(c);
      }
      return result.toString();
    }
    else {
      return s;
    }
  }

  public static String unescapeText(String s) {
    if (s.indexOf("&amp;") != -1 || s.indexOf("&lt;") != -1
        || s.indexOf("&quot;") != -1 || s.indexOf("&apos;") != -1
        || s.indexOf("&gt;") != -1) {
      StringBuffer result = new StringBuffer(s);
      int pos = 0;
      for (int i = 0; i < s.length(); i++) {
        if (result.indexOf("&amp;") != -1) {
          pos = result.indexOf("&amp;");
          result.replace(pos, pos + 5, "&");
        }
        else if (result.indexOf("&lt;") != -1) {
          pos = result.indexOf("&lt;");
          result.replace(pos, pos + 4, "<");
        }
        else if (result.indexOf("&quot;") != -1) {
          pos = result.indexOf("&quot;");
          result.replace(pos, pos + 6, "/"");
        }
        else if (result.indexOf("&apos;") != -1) {
          pos = result.indexOf("&apos;");
          result.replace(pos, pos + 6, "/'");
        }
        else if (result.indexOf("&gt;") != -1) {
          pos = result.indexOf("&gt;");
          result.replace(pos, pos + 4, ">");
        }
      }
      return result.toString();
    }
    else {
      return s;
    }
  }

  public static String fetchText(Node n) {
    if (n.getFirstChild() != null) {
      return n.getFirstChild().getNodeValue();
    }
    else {
      return "";
    }
  }

  public static Node updateAttrName(NodeFactory nf, Node n, String val) {
    //System.out.println(n.getNodeName() + ":" + n.getNodeValue());
    Node newnode = null;
    if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
      newnode = nf.getAttrNode(val, n.getNodeValue());
      Attr e = (Attr) n;
      e.removeChild( ( (Attr) n));
      e.appendChild( (Attr) newnode);
      System.out.println(newnode.getNodeName() + ":" + newnode.getNodeValue());
    }
    if (n.getNodeType() == Node.ELEMENT_NODE) {
      newnode = nf.getEleNode(val);
      NodeFactory.updateText(nf, newnode, NodeFactory.fetchText(n));
      for (int i = 0; i < n.getAttributes().getLength(); i++) {
        newnode.getAttributes().setNamedItem(n.getAttributes().item(i));
      }
      n.getParentNode().replaceChild(newnode, n);
    }
    return newnode;
  }

  public static Node updateAttrText(NodeFactory nf, Node n, String val) {
    //System.out.println(n.getNodeName() + ":" + n.getNodeValue());
    if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
      n.setNodeValue(val);
    }
    return n;
  }

  public static void updateText(NodeFactory nf, Node n, String val) {
    if (n.getFirstChild() != null) {
      n.getFirstChild().setNodeValue(val);
    }
    else {
      n.appendChild(nf.getTextNode(val));
    }
  }

  public void updateText(Node n, String val) {
    if (n.getFirstChild() != null) {
      n.getFirstChild().setNodeValue(val);
    }
    else {
      n.appendChild(getTextNode(val));
    }
  }
}

使用上面两个类的RegexPatternModel

package org.matcher;

import org.w3c.dom.*;
import javax.swing.table.*;
import java.util.*;
import javax.xml.xpath.*;
import org.xmlutil.NodeFactory;

/**
 * 该类是一个MVC中的M,用于生成匹配模式数据.
 * 源头是xml格式的文件:结构为:
 * <? xml version="1.0"?>
 * <patterns>
 * <pattern name="" value=""></pattern>
 * <pattern name="" value=""></pattern>
 * </patterns>
 */
public class RegexPatternModel
    extends AbstractTableModel { //DefaultTableModel
  private static String patternfile = "pattern.xml";
  private Document doc;
  private Node root;
  NodeFactory nf = new NodeFactory();
  private Vector vector;
  ResourceBundle uibundle = ResourceBundle.getBundle("regexuiname");
  String[] columnheader;

  public RegexPatternModel() {
    vector = new Vector();
    columnheader = new String[] {
        uibundle.getString("tablecolumn1"), uibundle.getString("tablecolumn2"),
        uibundle.getString("tablecolumn3")};
    doc = org.xmlutil.XmlBuilderStatic.getData(patternfile);
    nf.setDoc(doc);
    root = doc.getDocumentElement();
    handleAttr();
    try {
      jbInit();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  private void handleAttr() {
    Object[] members;
    Node node = null;
    try {
      NodeList nlist = (NodeList) org.xmlutil.XmlBuilderStatic.getXpath().
          evaluate("/patterns/pattern", doc,
                   javax.xml.xpath.XPathConstants.NODESET);
      for (int j = 0; j < nlist.getLength(); j++) {
        node = nlist.item(j);
        members = new Object[3];
        //members[0] = node.getAttributes().item(i).getNodeName();
        members[0] = node.getAttributes().getNamedItem("name").getNodeValue();
        members[1] = node.getAttributes().getNamedItem("value").getNodeValue();
        //System.out.println(members[0].toString() + ":" + members[1].toString());
        members[2] = node; //java.lang.ArrayStoreException: com.sun.org.apache.xerces.internal.dom.DeferredAttrImpl
        vector.add(members);
      }
    }
    catch (XPathExpressionException ex) {
      ex.printStackTrace();
    }
  }

  public void SaveXml() {
    //System.out.println("save");
    org.xmlutil.SaveXml.XmlSave(doc, this.patternfile, true);
  }

  public int getColumnCount() {
    return this.columnheader.length - 1;
  }

  public int getRowCount() {
    return this.vector.size();
  }

  public Object getValueAt(int row, int column) {
    return ( ( (Object[]) (vector.elementAt(row)))[column]);
  }

  public String getColumnName(int column) {
    return this.columnheader[column];
  }

  public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    if (this.vector == null) {
      return;
    }
    Node node = (Node) ( (Object[])this.vector.elementAt(rowIndex))[2];
    switch (columnIndex) {
      case 0:

        //members[rowIndex][0] = aValue.toString();
        ( (Object[]) vector.elementAt(rowIndex))[0] = aValue.toString();
        node.getAttributes().getNamedItem("name").setNodeValue(aValue.toString());

        //NodeFactory.updateText(nf,node,aValue.toString());
        break;
      case 1:
        ( (Object[]) vector.elementAt(rowIndex))[1] = aValue.toString();
        node.getAttributes().getNamedItem("value").setNodeValue(aValue.toString());
    }
    fireTableCellUpdated(rowIndex, columnIndex);
  }

  /**
   * 为元素添加属性,注意,如果属性名称与已经存在,则使用新属性替换这个已存在的属性.
   *
   */
  public void AddRow() {
    Object[] objs = new Object[3];
    objs[0] = "proname";
    objs[1] = "val";
    Node node = nf.getEleNode("pattern");
    nf.getAttrNode(node, "name", objs[0].toString());
    nf.getAttrNode(node, "value", objs[1].toString());
    objs[2] = node;
    root.appendChild(node);
    vector.add(objs);
    this.fireTableDataChanged();
  }

  public void deleteRow(int row) {
    if (row == -1)
      return;
    Node n = (Node) ( (Object[]) vector.elementAt(row))[2];
    root.removeChild(n);
    vector.remove(row);
    this.fireTableDataChanged();
  }

  public void deleteRow() {
    deleteRow(vector.size());
  }

  public boolean isCellEditable(int row, int column) {
    switch (column) {
      case 0:
        return true;
      case 1:
        return true;
      default:
        return true;
    }
  }

  private void jbInit() throws Exception {
  }
}

一个简单的组件类RegexProperty

package org.matcher;

import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ListSelectionModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class RegexProperty
    extends javax.swing.JPanel {

  JScrollPane jScrollPane1 = new JScrollPane();
  JButton jButton1 = new JButton();
  JButton jButton2 = new JButton();
  JPanel jPanel1 = new JPanel();
  BorderLayout borderLayout1 = new BorderLayout();
  JTable jTable1 = new JTable();
  RegexPatternModel rgmodel;
  private String pattern = "";

  public RegexProperty() {
    try {
      jbInit();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  private void jbInit() throws Exception {
    rgmodel = new RegexPatternModel();
    jButton1.setText("添加");
    jButton1.addActionListener(new RegexProperty_jButton1_actionAdapter(this));
    jButton2.setText("删除");
    jButton2.addActionListener(new RegexProperty_jButton2_actionAdapter(this));
    this.setLayout(borderLayout1);
    jScrollPane1.getViewport().add(jTable1);
    jPanel1.add(jButton1);
    jPanel1.add(jButton2);
    jTable1.setModel(rgmodel);
    jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jTable1.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        printDebugData(jTable1, e);
      }
    });

    this.add(jScrollPane1, java.awt.BorderLayout.CENTER);
    this.add(jPanel1, java.awt.BorderLayout.SOUTH);
  }

  private void printDebugData(JTable table, MouseEvent e) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    int row = table.getSelectedRow();
    javax.swing.table.TableModel model = table.getModel();
    this.setPattern(model.getValueAt(row, 1).toString());
  }

  public String getPattern() {
    return this.pattern;
  }

  public void setPattern(String p) {
    pattern = p;
  }

  public void jButton1_actionPerformed(ActionEvent e) {
    rgmodel.AddRow();
  }

  public void jButton2_actionPerformed(ActionEvent e) {
    rgmodel.deleteRow(jTable1.getSelectedRow());
  }
  public void save(){
    rgmodel.SaveXml();
  }
}

class RegexProperty_jButton1_actionAdapter
    implements ActionListener {
  private RegexProperty adaptee;
  RegexProperty_jButton1_actionAdapter(RegexProperty adaptee) {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) {
    adaptee.jButton1_actionPerformed(e);
  }
}

class RegexProperty_jButton2_actionAdapter
    implements ActionListener {
  private RegexProperty adaptee;
  RegexProperty_jButton2_actionAdapter(RegexProperty adaptee) {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) {
    adaptee.jButton2_actionPerformed(e);
  }
}

最后是框架ExtractInfoFrame类

package org.matcher;

import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.util.ResourceBundle;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExtractInfoFrame
    extends JFrame {
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  JPanel jPanel2 = new JPanel();
  JPanel jPanel3 = new JPanel();
  JToolBar jToolBar1 = new JToolBar();
  BorderLayout borderLayout2 = new BorderLayout();
  JLabel jLabel1 = new JLabel();
  JTextField jTextField1 = new JTextField();
  JButton jButton1 = new JButton();
  JLabel jLabel2 = new JLabel();
  BorderLayout borderLayout3 = new BorderLayout();
  JSplitPane jSplitPane1 = new JSplitPane();
  BorderLayout borderLayout4 = new BorderLayout();
  JPanel jPanel4 = new JPanel();
  JScrollPane jScrollPane2 = new JScrollPane();
  JPanel jPanel5 = new JPanel();
  BorderLayout borderLayout5 = new BorderLayout();
  JTextArea jTextArea1 = new JTextArea();
  JTextArea jTextArea2 = new JTextArea();
  JComboBox jComboBox1 = new JComboBox();
  JLabel jLabel3 = new JLabel();
  JButton jButton2 = new JButton();
  GridBagLayout gridBagLayout1 = new GridBagLayout();
  JSplitPane jSplitPane2 = new JSplitPane();
  JScrollPane jScrollPane3 = new JScrollPane();
  JTextArea jTextArea3 = new JTextArea();
  RegexProperty rp = new RegexProperty();
  JMenuBar jMenuBar1 = new JMenuBar();
  JMenu jMenu1 = new JMenu();
  JMenuItem jMenuItem1 = new JMenuItem();
  JMenuItem jMenuItem2 = new JMenuItem();
  ResourceBundle uibundle=ResourceBundle.getBundle("regexuiname");

  public ExtractInfoFrame() {
    try {
      //this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
      this.addWindowListener(new winAdapter(this));
      //uibundle=ResourceBundle.getBundle("regexuiname.properties");
      this.setTitle(uibundle.getString("maintitle") );
      jbInit();
    }
    catch (Exception exception) {
      exception.printStackTrace();
    }
  }

  private void jbInit() throws Exception {
    getContentPane().setLayout(borderLayout1);
    jButton2.addActionListener(new ExtractInfoFrame_jButton2_actionAdapter(this));
    jSplitPane1.setOpaque(false);
    jSplitPane1.setOneTouchExpandable(true);
    jSplitPane1.setDividerLocation(140);
    jSplitPane1.setDividerSize(8);
    jTextArea3.setText("");
    jSplitPane2.setOneTouchExpandable(true);
    jSplitPane2.setDividerLocation(0);
    jSplitPane2.setDividerSize(8);
    this.setJMenuBar(jMenuBar1);
    jMenu1.setText(uibundle.getString("mnufile"));
    jMenuItem1.setText(uibundle.getString("submnusave"));
    jMenuItem1.addActionListener(new ExtractInfoFrame_jMenuItem1_actionAdapter(this));
    jMenuItem2.setText(uibundle.getString("submnuexit"));
    jMenuItem2.addActionListener(new ExtractInfoFrame_jMenuItem2_actionAdapter(this));
    this.getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);
    jPanel2.setLayout(borderLayout3);
    this.getContentPane().add(jPanel3, java.awt.BorderLayout.NORTH);
    jPanel3.setLayout(borderLayout2);
    jLabel1.setText(uibundle.getString("sourcelabel"));
    jTextField1.setText("http://www.163.com/index.html");
    jButton1.setText(uibundle.getString("cmdexec"));
    jButton1.addActionListener(new ExtractInfoFrame_jButton1_actionAdapter(this));
    jLabel2.setText(" ");
    jPanel1.setLayout(borderLayout4);
    jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT);
    jSplitPane1.setLastDividerLocation(100);
    jPanel4.setLayout(borderLayout5);
    jTextArea1.setText("(<img.*//S>)");
    jTextArea2.setText("");
    jLabel3.setText(uibundle.getString("selectregexlabel"));
    jButton2.setText(uibundle.getString("cmdresolve"));
    jPanel5.setLayout(gridBagLayout1);
    jPanel3.add(jToolBar1, java.awt.BorderLayout.CENTER);
    jToolBar1.add(jLabel1);
    jToolBar1.add(jTextField1);
    jToolBar1.add(jButton1);
    jPanel2.add(jLabel2, java.awt.BorderLayout.CENTER);
    jSplitPane1.add(jPanel4, JSplitPane.LEFT);
    jPanel5.add(jComboBox1, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
        , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
        new Insets(0, 0, 0, 0), 0, 0));
    jPanel5.add(jButton2, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
                                                 , GridBagConstraints.WEST,
                                                 GridBagConstraints.HORIZONTAL,
                                                 new Insets(0, 0, 0, 0), 0, 0));
    jPanel5.add(jLabel3, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                                                , GridBagConstraints.WEST,
                                                GridBagConstraints.HORIZONTAL,
                                                new Insets(0, 0, 0, 0), 0, 0));
    jSplitPane1.add(rp, JSplitPane.RIGHT);
    jSplitPane2.add(jScrollPane3, JSplitPane.LEFT);
    jScrollPane3.getViewport().add(jTextArea3);

    jPanel4.add(jScrollPane2, java.awt.BorderLayout.CENTER);
    jPanel4.add(jPanel5, java.awt.BorderLayout.SOUTH);
    jScrollPane2.getViewport().add(jTextArea2);

    this.getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
    jSplitPane2.add(jSplitPane1, JSplitPane.RIGHT);
    jPanel1.add(jSplitPane2, java.awt.BorderLayout.CENTER);
    jMenuBar1.add(jMenu1);
    jMenu1.add(jMenuItem1);
    jMenu1.add(jMenuItem2);
  }

  public void exitSave() { //WindowEvent e
    rp.save();
    //System.out.println("quit");
    System.exit(0);
  }

  /**
   * fetch source text
   * @param e ActionEvent
   */
  public void jButton1_actionPerformed(ActionEvent e) {
    try {
      //this.setCursor(Cursor.WAIT_CURSOR);
      this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
      jTextArea3.setText(getString(this.jTextField1.getText()));
    }
    catch (Exception ex) {
      this.jLabel2.setText(ex.getMessage());
    }
    finally {
      this.setCursor(Cursor.getDefaultCursor());
    }
  }
  public String getString(String url1) {
    try {
      URL url = new URL(url1);
      BufferedReader br = new BufferedReader(new InputStreamReader(url.
          openStream()));
      StringBuffer sb = new StringBuffer();
      String tm;
      while ( (tm = br.readLine()) != null) {
        sb.append(tm + "/n");
      }
      return sb.toString();
    }
    catch (Exception ex) {

    }
    return null;
  }
  /**
   * gain resolve text
   * @param e ActionEvent
   */
  public void jButton2_actionPerformed(ActionEvent e) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    getSpecStr(jTextArea3.getText(), rp.getPattern());
    this.setCursor(Cursor.getDefaultCursor());
  }

  private String getSpecStr(String str, String model) {
    StringBuffer tm = new StringBuffer();
    java.util.regex.Pattern p = null;
    int counter = 0;
    try {
      this.jLabel2.setText(model);
      p = java.util.regex.Pattern.compile(model);
    }
    catch (Exception ex) {
      jLabel2.setText(ex.getMessage());
      return "";
    }
    java.util.regex.Matcher m = p.matcher(str);
    while (m.find()) {
      for (int i = 0; i < m.groupCount(); i++) {
        if (m.group(i) != null) {
          tm.append("总" + m.groupCount() + "," + i + ":" + m.group(i));
          tm.append("/n");
        }
      }
      counter++;
    }
    this.jLabel2.setText(this.jLabel2.getText() + " total " + counter);
    jTextArea2.setText(tm.toString());
    return tm.toString();
  }

  public static void main(String[] args) {
    ExtractInfoFrame ef = new ExtractInfoFrame();
    org.common.WindowUtilities.sizeWindowOnScreen(ef, 0.5d, 0.5d);
    org.common.WindowUtilities.centerWindowOnScreen(ef);
    ef.setVisible(true);
  }

  public void jMenuItem2_actionPerformed(ActionEvent e) {
    this.exitSave();
  }

  public void jMenuItem1_actionPerformed(ActionEvent e) {
    rp.save();
  }
}

class ExtractInfoFrame_jMenuItem2_actionAdapter
    implements ActionListener {
  private ExtractInfoFrame adaptee;
  ExtractInfoFrame_jMenuItem2_actionAdapter(ExtractInfoFrame adaptee) {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) {
    adaptee.jMenuItem2_actionPerformed(e);
  }
}

class ExtractInfoFrame_jMenuItem1_actionAdapter
    implements ActionListener {
  private ExtractInfoFrame adaptee;
  ExtractInfoFrame_jMenuItem1_actionAdapter(ExtractInfoFrame adaptee) {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) {
    adaptee.jMenuItem1_actionPerformed(e);
  }
}

class ExtractInfoFrame_jButton2_actionAdapter
    implements ActionListener {
  private ExtractInfoFrame adaptee;
  ExtractInfoFrame_jButton2_actionAdapter(ExtractInfoFrame adaptee) {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) {
    adaptee.jButton2_actionPerformed(e);
  }
}

class ExtractInfoFrame_jButton1_actionAdapter
    implements ActionListener {
  private ExtractInfoFrame adaptee;
  ExtractInfoFrame_jButton1_actionAdapter(ExtractInfoFrame adaptee) {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) {
    adaptee.jButton1_actionPerformed(e);
  }
}

class winAdapter
    extends WindowAdapter {
  ExtractInfoFrame ef;
  public winAdapter(ExtractInfoFrame e) {
    ef = e;
  }

  public void windowClosing(WindowEvent e) {
    ef.exitSave();
  }

  public void windowClosed(WindowEvent e) {
    ef.exitSave();
  }
}

国际化资源:

regexuiname.properties

maintitle=Regex Handler
sourcelabel=source name
cmdexec=exec fetch
selectregexlabel=select reg pattern
cmdresolve=exec resolve
mnufile=File
submnusave=Save
submnuexit=Exit
tablecolumn1=patternname
tablecolumn2=patterncontent
tablecolumn3=bindobj
tablecolumns=patternname,patterncontent,bindobj

regexuiname_zh_CN.properties

maintitle=/u6a21/u5f0f/u5904/u7406/u5668
sourcelabel=/u9009/u62e9/u6e90/u5934
cmdexec=/u63d0/u53d6/u6e90/u4e32
selectregexlabel=/u9009/u62e9/u6b63/u5219/u6a21/u5f0f
cmdresolve=/u6267/u884c/u5206/u6790
mnufile=/u6587/u4ef6
submnusave=/u4fdd/u5b58
submnuexit=/u9000/u51fa
tablecolumn1=/u6a21/u5f0f/u540d/u79f0
tablecolumn2=/u6a21/u5f0f/u5185/u5bb9
tablecolumn3=/u7ed1/u5b9a/u5bf9/u8c61
tablecolumns=/u6a21/u5f0f/u540d/u79f0,/u6a21/u5f0f/u5185/u5bb9,/u7ed1/u5b9a/u5bf9/u8c61

保存模式的文件pattern.xml,下面是一些样本:

<?xml version="1.0" encoding="UTF-8"?>
<patterns>
<pattern name="匹配html元素" value="&lt;(.*)&gt;.*&lt;///1&gt;"/>
<pattern name="匹配html标记属性后的=value" value="(=/w+/s)|(=/w+)|(=/#/w+/s)"/>
<pattern name="匹配img元素" value="(&lt;img.*/S&gt;)"/>
<pattern name="proname" value="(=/w+)"/>
<pattern name="proname" value="(/w+)|(/#/w+)"/>
<pattern name="匹配空行" value="^/[ /t]*$"/>
<pattern name="proname" value="&lt;/s* http /*([^&gt;]*) /s*&gt;"/>
<pattern name="font" value="&lt;/s* font /*([^&gt;]*) /s*&gt;"/>
<pattern name="proname" value="([A-Z]{4})/(([0-9]{3})/)"/>
<pattern name="proname" value="(=/w+/s)|(=/w+)|(=/#/w+/s)"/>
<pattern name="proname" value="(&lt;a/shref=/w*)|(&lt;img/ssrc/w&gt;)"/>
<pattern name="proname" value="([&lt;a/s.*href=/w+:/w+@/d+.com&gt;&lt;/a&gt;]+)"/>
<pattern name="proname" value="(&lt;img/s*src/s*&gt;)|(&lt;img/s*/w+/s*&gt;)"/>
<pattern name="proname" value="(&lt;a/s)"/>
<pattern name="proname" value="(&lt;img/ssrc='/w+/S+/s/w+/S&lt;///1&gt;)"/>
<pattern name="proname" value="(&lt;a/s.*href=/w+:/w+@/d+.com&gt;&lt;/a&gt;)"/>
<pattern name="proname" value="http:///w./d.com//w"/>
<pattern name="proname" value="(&lt;a.*a&gt;)"/>
<pattern name="proname" value="(&lt;a.*&lt;img.*//S&gt;)"/>
<pattern name="proname" value="(&lt;a/s.*href=/w+:/w+@/d+.com&gt;&lt;/a&gt;)|(&lt;a.*//S&gt;)"/>
<pattern name="proname" value="(/s&lt;a.*//S&gt;)|(&lt;img.*/S&gt;)"/>
<pattern name="proname" value="(&lt;img.*/S&gt;)"/>
<pattern name="proname" value="(/s&lt;a.*/S&gt;)"/>
<pattern name="proname" value="(/s&lt;a.*//S&gt;/n/S&gt;)"/>
<pattern name="proname" value="(?!/D*/&quot;)(/S*)(?=/&quot;)"/>
<pattern name="proname" value="(?!/D*/&quot;)http(/S*)(?=/&quot;)"/>
<pattern name="proname" value="(?!/[)(/D*)(?=/])"/>
<pattern name="proname" value="(&quot;=/?(.+)/?(B|Q)/?(.+)/?=&quot;)"/>
<pattern name="proname" value="(?!=/?)(/D*)(?=/?=)"/>
<pattern name="proname" value="(&lt;img src=/&quot;/S+/&quot;&gt;)"/>
<pattern name="proname" value="(/&quot;(/S*)/&quot;)|/'/S*/'"/>
<pattern name="proname" value="(href=/S*)"/>
<pattern name="proname" value="(=/w+/s)|(=/w+)|(=/#/w+/s)"/>
<pattern name="proname" value="(href=/S*)"/>
<pattern name="proname" value="='(/S*(/w+)|(/d*))"/>
<pattern name="proname" value="(=.((/S*/w+)|(/s*).))|(=/#/w+/s)"/>
<pattern name="proname" value="(http)?"/>
<pattern name="proname" value="(^./)"/>
<pattern name="proname" value="../"/>
<pattern name="proname" value="='(/S*(/w+)|(/d*))'"/>
<pattern name="proname" value="(=.((/S*/w+)|(/s*).))|(=/#/w+/s)"/>
<pattern name="proname" value="(/S*base/S*)"/>

<pattern name="name=&quot;sub&quot; 取得引号内的内容,不包括引号" value="(?!&quot;)(/w+)(?=&quot;)"/>
<pattern name="name=&quot;sub&quot; 取得两个单词" value="(/w+)"/>
<pattern name="name=&quot;sub&quot; 取得包括引号在内的内容" value="&quot;(/w+)&quot;"/>
<pattern name="proname" value="(/:/s+/D+/n)"/>
<pattern name="proname" value="^/[ /n]*$"/>
<pattern name="空白行" value="^$"/>
<pattern name="proname" value="(?!&quot;)(/w*)(?=&quot;)"/>
<pattern name="proname" value="(?!name=&quot;)(/w*)(?=&quot;;)"/>
<pattern name=" filename=&quot;C:/Documents and Settings/Administrator/×ÀÃæ/110-P230.txt&quot;" value="(filename=&quot;/D*/S*)(?=&quot;)"/>
<pattern name="proname" value="(/w*(&quot;);)"/>
<pattern name="proname" value="&quot;{a-z0-9_}*&quot;"/>
<pattern name="proname" value="(=.((/S*/w+)|(/s*).))"/>
<pattern name="Content-Type: text/plain" value="(?!Content-Type:)(/s/S*)"/>
<pattern name="proname" value="Content-Type:(/s/S*)"/>
</patterns>


原文链接: http://blog.csdn.net/keepeye/article/details/465891

你可能感兴趣的:(正则表达式测试工具)