??xml version="1.0" encoding="utf-8" standalone="yes"?>
package org.tatan.mail;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.Session;
import javax.mail.MessagingException;
import javax.mail.Transport;
public class SendHtmlMail {
public static void sendMessage(String smtpHost,
String from, String to,
String subject, String messageText)
throws MessagingException,java.io.UnsupportedEncodingException {
// Step 1: Configure the mail session
System.out.println("Configuring mail session for: " + smtpHost);
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP验证
props.setProperty("mail.smtp.host", smtpHost);//指定SMTP服务?BR> props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台昄debug信息
// Step 2: Construct the message
System.out.println("Constructing message - from=" + from + " to=" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
testMessage.setSentDate(new java.util.Date());
testMessage.setSubject(MimeUtility.encodeText(subject,"gb2312","B"));
testMessage.setContent(messageText, "text/html;charset=gb2312");
System.out.println("Message constructed");
// Step 3: Now send the message
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost, "webmaster", "password");
transport.sendMessage(testMessage, testMessage.getAllRecipients());
transport.close();
System.out.println("Message sent!");
}
public static void main(String[] args) {
String smtpHost = "localhost";
String from = "webmaster@mymail.com";
String to = "mfc42d@sohu.com";
String subject = "html邮g试"; //subject javamail自动转码
StringBuffer theMessage = new StringBuffer();
theMessage.append("<h2><font color=red>q倒霉孩子</font></h2>");
theMessage.append("<hr>");
theMessage.append("<i>q年失望q年?lt;/i>");
try {
SendHtmlMail.sendMessage(smtpHost, from, to, subject, theMessage.toString());
}
catch (javax.mail.MessagingException exc) {
exc.printStackTrace();
}
catch (java.io.UnsupportedEncodingException exc) {
exc.printStackTrace();
}
}
}
邮g?参见RFC822QRFC2047)只能包含US-ASCII字符?BR>邮g头中M包含非US-ASCII字符的部分必进行编码,使其只包含US-ASCII字符?BR>但是java mail可以Ҏ(gu)JVM发送中文邮件自行编码,Q用它自带的MimeUtilitycȝencodeTextҎ(gu)对中文信息进行编码也可以?BR>邮g正文必须有charset=gb2312否则?BR>Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit
打开邮gZؕ?讄charset=gb2312?BR>Content-Type: text/html;charset=gb2312
Content-Transfer-Encoding: quoted-printable
它不能用MimeUtility里的Ҏ(gu)来编码?BR>邮g正文的编码方式的信息是要攑֜Content-Transfer-Encodingq个邮g头参C的,
而MimeUtility里面的方法是编码方式的信息攑֜~码后的正文内容中?BR>所以如果你Ҏ(gu)文也用MimeUtilityq行处理Q那么其他邮件程序就不会(x)正常昄你编码的邮gQ?BR>因ؓ(f)其他邮g软g如outlook,foxmail只会(x)Ҏ(gu)Content-Transfer-Encodingq个里面的信息来寚w件正文进行解码?/P>
import javax.mail.Session;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;
public class SendAttachMail {
public static void sendMessage(String smtpHost,
String from, String to,
String subject, String messageText,
String fileName)
throws MessagingException {
// Step 1: Configure the mail session
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP验证
props.setProperty("mail.smtp.host", smtpHost);//指定SMTP服务?BR> props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台昄debug信息
// Step 2: Construct the message
System.out.println("Constructing message - from=" + from + " to=" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
testMessage.setSentDate(new java.util.Date());
testMessage.setSubject(subject);
// Step 3: Create a body part to hold the "text" portion of the message
System.out.println("Constructing 'text' body part");
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(messageText,"text/html;charset=gb2312");
// Step 4: Create a body part to hold the "file" portion of the message
System.out.println("Attaching 'file' body part: " + fileName);
MimeBodyPart fileBodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("c:\\a.rar");
fileBodyPart.setDataHandler(new DataHandler(fds));
fileBodyPart.setFileName(fds.getName());
System.out.println("Finished attaching file");
// Step 5: Create a Multipart/container and add the parts
Multipart container = new MimeMultipart();
container.addBodyPart(textBodyPart);
container.addBodyPart(fileBodyPart);
// Step 6: Add the Multipart to the actual message
testMessage.setContent(container);
System.out.println("Message constructed");
// Step 7: Now send the message
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost, "webmaster", "password");
transport.sendMessage(testMessage, testMessage.getAllRecipients());
transport.close();
System.out.println("Message sent!");
}
public static void main(String[] args) {
String fileName = "a.rar";
String smtpHost = "localhost";
String from = "webmaster@mymail.com";
String to = "mfc42d@sohu.com";
String subject = "html邮g附g试"; //subject javamail自动转码
StringBuffer theMessage = new StringBuffer();
theMessage.append("<h2><font color=red>q倒霉孩子</font></h2>");
theMessage.append("<hr>");
theMessage.append("<i>q年失望q年?lt;/i>");
try {
SendAttachMail.sendMessage(smtpHost, from, to, subject, theMessage.toString(), fileName);
}
catch (javax.mail.MessagingException exc) {
exc.printStackTrace();
}
}
}
q个是因为Runtime.getRuntime().exec()要自己去处理stdout和stderr的?nbsp;
所以如果你惌E序正常q行的话Q请务必上q用别的U程取走?nbsp;
>test.bat
haha
exit 99
>RuntimeTest.java
public class RuntimeTest {
public static void main(String[] args) {
try {
Process process=Runtime.getRuntime().exec("test.bat");
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
// kick off stderr
errorGobbler.start();
StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "STDOUT");
// kick off stdout
outGobbler.start();
process.waitFor();
System.out.println(process.exitValue());
} catch(Exception e) {}
}
}
>StreamGobbler.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
public class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;
StreamGobbler(InputStream is, String type) {
this(is, type, null);
}
StreamGobbler(InputStream is, String type, OutputStream redirect) {
this.is = is;
this.type = type;
this.os = redirect;
}
public void run() {
try {
PrintWriter pw = null;
if (os != null)
pw = new PrintWriter(os);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
if (pw != null)
pw.println(line);
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
自己mark一?/P>
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT SYSDATE FROM DUAL");
if (rs.next()) {
sysTime = rs.getTimestamp("SYSDATE");
}
} catch (Exception e) {
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
}
}
return sysTime;
}
最好的办法使用long存时_(d)使用Calendar 处理Q就是表C日期时间不直观?BR>2.字符串{化时_(d)注意不能判断旉输入是否正确Q判断时间输入是否正,请用正则?BR>try
{
String st="2005-13-32 12:00";
java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date starttime = df.parse(st);
System.out.println(starttime.toString());
}
catch(Exception ex)
{
}
不要搞?jin)try-catch的功能。只有程序或pȝ抛出?jin)异常,try-catch才能捕获 Q得到Wed Feb 01 00:00:00 CST 2006
q样操作是错误的QTimestamp是java.util.DateQ会(x)得到java.lang.ClassCastExceptionQ你犯了(jin)向下转型的错误?/P>
try
{
String st="2005-13-32 12:00";
java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Timestamp starttime =(Timestamp) df.parse(st);
System.out.println(starttime.toString());
}
catch(Exception ex)
{
ex.printStackTrace();
}
应该使用
try {
String st = "2005-12-2 12:00:00";
Timestamp starttime = Timestamp.valueOf(st);
System.out.println(starttime.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
?BR> import java.sql.*;
import java.util.*;
public class CreateTimestamp {
public static void main(String [] args) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 45);
cal.set(Calendar.SECOND, 30);
cal.set(Calendar.MILLISECOND, 0);
long millis = cal.getTime().getTime();
System.out.println("milliseconds in millis = " + millis);
java.sql.Timestamp ts = new java.sql.Timestamp(millis);
System.out.println("Timestamp ts before setting nanos = " + ts);
ts.setNanos(500);
System.out.println("Timestamp ts with nanos set = " + ts);
}
}
下面l出javadoc的方?BR>1. java.sql.Date.valueOf(java.lang.String)
public static Date valueOf(String s)
Converts a string in JDBC date escape format to a Date value.
Parameters:
s - a String object representing a date in in the format "yyyy-mm-dd"
Returns:
a java.sql.Date object representing the given date
Throws:
IllegalArgumentException - if the date given is not in the JDBC date escape format (yyyy-mm-dd)
2. java.sql.Time.valueOf(java.lang.String)
public static Time valueOf(String s)
Converts a string in JDBC time escape format to a Time value.
Parameters:
s - time in format "hh:mm:ss"
Returns:
a corresponding Time object
3. java.sql.Timestamp.valueOf(java.lang.String)
public static Timestamp valueOf(String s)
Converts a String object in JDBC timestamp escape format to a Timestamp value.
Parameters:
s - timestamp in format yyyy-mm-dd hh:mm:ss.fffffffff
Returns:
corresponding Timestamp value
Throws:
IllegalArgumentException - if the given argument does not have the format yyyy-mm-dd hh:mm:ss.fffffffff
//取得剩余天数
SimpleDateFormat df=new SimpleDateFormat("yyyymmdd");
Date d0=new java.util.Date();
Date d1=df.parse(end_date);
long time0=d0.getTime();
long time1=d1.getTime();
System.out.println((time1-time0)/(1000*60*60*24));
q样两个时间相差的天数比较?
/**
* 计算两个日期之间相差的天?BR> *
* @param date1
* @param date2
* @return
*/
public static int diffdates(Date date1, Date date2) {
int result = 0;
ElapsedTime et = new ElapsedTime();
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc1.setTime(date1);
gc2.setTime(date2);
result = et.getDays(gc1, gc2);
return result;
}
然后ElapseTime中的Ҏ(gu)是:(x)
public int getDays(GregorianCalendar g1, GregorianCalendar g2) {
int elapsed = 0;
GregorianCalendar gc1, gc2;
if (g2.after(g1)) {
gc2 = (GregorianCalendar) g2.clone();
gc1 = (GregorianCalendar) g1.clone();
} else {
gc2 = (GregorianCalendar) g1.clone();
gc1 = (GregorianCalendar) g2.clone();
}
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
while (gc1.before(gc2)) {
gc1.add(Calendar.DATE, 1);
elapsed++;
}
return elapsed;
}
其实使用joda最?/FONT>
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = Period.days(2);
return datetimeRented.plus(rentalPeriod).isBeforeNow()
}
原著QSteve Mansour
sman@scruznet.com
Revised: June 5, 1999
(copied by jm /at/ jmason.org from http://www.scruz.net/%7esman/regexp.htm, after the original disappeared! )
译QNeo Lee
neo.lee@gmail.com
2004q?0?6?/FONT>
译者按Q原文因为年代久q,文中很多链接早已q期Q主要是关于vi、sed{工L(fng)介绍和手册)(j)Q本译文中已此c链接删除,如需(g)查这些链接可以查看上面链接的原文。除此之外基本照原文直译Q括号中有“译者按”的部分是译者补充的说明。如有内Ҏ(gu)面的问题L(fng)接和Steve Mansor联系Q当?dng)如果你只写中文,也可以和我联pR?/P>
什么是正则表达?/A>
范例
?/A>
中Q神奇的咒语Q?/A>
困难Q不可思议的象形文字)(j)
不同工具中的正则表达?/A>
我们在如下的章节中利用一些例子来解释正则表达式的用法Q绝大部分的例子是基?B>vi中的文本替换命o(h)?B>grep文g搜烦(ch)命o(h)来书写的Q不q它们都是比较典型的例子Q其中的概念可以在sed、awk、perl和其他支持正则表辑ּ的编E语a中用。你可以看看不同工具中的正则表达?/A>q一节,其中有一些在别的工具中用正则表辑ּ的例子。还有一个关于vi中文本替换命令(sQ的单说?/A>附在文后供参考?/P>
在最单的情况下,一个正则表辑ּ看上d是一个普通的查找丌Ӏ例如,正则表达?testing"中没有包含Q何元字符Q,它可以匹?testing"?123testing"{字W串Q但是不能匹?Testing"?/P>
要想真正的用好正则表辑ּQ正的理解元字W是最重要的事情。下表列Z(jin)所有的元字W和对它们的一个简短的描述?
正则表达式基
正则表达式由一些普通字W和一?I>元字W(metacharactersQ?/I>l成。普通字W包括大写的字母和数字Q而元字符则具有特D的含义Q我们下面会(x)l予解释?
元字W?/I> | 描述 | |
---|---|---|
|
| |
|
匚wM单个字符。例如正则表辑ּr.t匚wq些字符Ԍ(x)rat?I>rut?I>r tQ但是不匚wroot?nbsp; | |
|
匚w行结束符。例如正则表辑ּweasel$ 能够匚w字符?He's a weasel"的末,但是不能匚w字符?They are a bunch of weasels."?nbsp; | |
|
匚w一行的开始。例如正则表辑ּ^When in能够匚w字符?When in the course of human events"的开始,但是不能匚w"What and When in the"?/I> | |
|
匚w0或多个正好在它之前的那个字符。例如正则表辑ּ.*意味着能够匚wL数量的Q何字W?/TD> | |
|
q是引用府,用来这里列出的q些元字W当作普通的字符来进行匹配。例如正则表辑ּ\$被用来匹配美元符P而不是行,cM的,正则表达?TT>\.用来匚w点字W,而不是Q何字W的通配W?/TD> | |
[c1-c2] [^c1-c2] |
匚w括号中的M一个字W。例如正则表辑ּr[aou]t匚wrat?I>rot?I>rutQ但是不匚wret。可以在括号中用连字符-来指定字W的区间Q例如正则表辑ּ[0-9]可以匚wM数字字符Q还可以制定多个区间Q例如正则表辑ּ[A-Za-z]可以匚wM大小写字母。另一个重要的用法是“排除”,要想匚w除了(jin)指定区间之外的字W——也是所谓的补集——在左边的括号和W一个字W之间用^字符Q例如正则表辑ּ[^269A-Z] 匹配除???和所有大写字母之外的M字符?/TD> | |
|
匚w词(wordQ的开始(\<Q和l束Q\>Q。例如正则表辑ּ\<the能够匚w字符?for the wise"中的"the"Q但是不能匹配字W串"otherwise"中的"the"?STRONG>注意Q这个元字符不是所有的软g都支持的?/TD> | |
|
?\( ?\) 之间的表辑ּ定义为“组”(groupQ,q且匹配这个表辑ּ的字W保存到一个(f)时区域(一个正则表辑ּ中最多可以保?个)(j)Q它们可以用 \1 ?B>\9 的符h引用?/TD> | |
|
两个匹配条件进行逻辑“或”(OrQ运。例如正则表辑ּ(him|her) 匚w"it belongs to him"?it belongs to her"Q但是不能匹?it belongs to them."?STRONG>注意Q这个元字符不是所有的软g都支持的?/TD> | |
|
匚w1或多个正好在它之前的那个字符。例如正则表辑ּ9+匚w9?9?99{?STRONG>注意Q这个元字符不是所有的软g都支持的?/TD> | |
|
匚w0?个正好在它之前的那个字符?STRONG>注意Q这个元字符不是所有的软g都支持的?/TD> | |
\{i,j\} |
匚w指定数目的字W,q些字符是在它之前的表达式定义的。例如正则表辑ּA[0-9]\{3\} 能够匚w字符"A"后面跟着正好3个数字字W的Ԍ例如A123、A348{,但是不匹配A1234。而正则表辑ּ[0-9]\{4,6\} 匚wq箋(hu)的Q?个?个或?个数字字W?STRONG>注意Q这个元字符不是所有的软g都支持的?/TD> |
最单的元字W是点,它能够匹配Q何单个字W(注意?/STRONG>包括新行W)(j)。假定有个文件test.txt包含以下几行内容Q?/P>
要想匚w行首的字W要使用抑扬字符Q?EM>^Q——又是也被叫做插入符。例如,x(chng)到text.txt中行?he"打头的行Q你可能?x)先用简单表辑ּheQ但是这?x)匹配第三行?B>theQ所以要使用正则表达?B>^heQ它只匹配在行首出现?B>h? 有时候指定“除?jin)×××都匚w”会(x)比较Ҏ(gu)辑ֈ目的Q当抑扬字符Q?EM>^Q出现在Ҏ(gu)号中是,它表C“排除”,例如要匹?B>he Q但是排除前面是t or s的情性(也就?B>the?B>sheQ,可以使用Q?B>[^st]he? 可以使用Ҏ(gu)h指定多个字符区间。例如正则表辑ּ[A-Za-z]匚wM字母Q包括大写和写的;正则表达?B>[A-Za-z][A-Za-z]* 匚w一个字母后面接着0或者多个字母(大写或者小写)(j)。当然我们也可以用元字符+做到同样的事情,也就是:(x)[A-Za-z]+ Q和[A-Za-z][A-Za-z]*完全{h(hun)。但是要注意元字W?B>+ q不是所有支持正则表辑ּ的程序都支持的。关于这一点可以参考后面的正则表达式语法支持情?/A>?/P>
要指定特定数量的匚wQ要使用大括P注意必须使用反斜杠来转义Q。想匚w所?B>100?B>1000的实例而排?B>10?B>10000Q可以用:(x)10\{2,3\}Q这个正则表辑ּ匚w数字1后面跟着2或??的模式。在q个元字W的使用中一个有用的变化是忽略第二个数字Q例如正则表辑ּ0\{3,\} 匹配至?个连l的0?/P>
q里有一些有代表性的、比较简单的例子?
所有方法foo(a,b,c)的实例改为foo(b,a,c)。这里a、b和c可以是Q何提供给Ҏ(gu)foo()的参数。也是说我们要实现q样的{换:(x)
下面q条替换命o(h)能够实现q一法Q?/P>
现在让我们把它打散来加以分析。写?gu)个表辑ּ的基本思\是找出foo()和它的括号中的三个参数的位置。第一个参数是用这个表辑ּ来识别的Q:(x)\([^,]*\)Q我们可以从里向外来分析它:(x)
现在正是指出一个用正则表辑ּ常见错误的最x(chng)机。ؓ(f)什么我们要使用[^,]*q样的一个表辑ּQ而不是更加简单直接的写法Q例如:(x).*Q来匚wW一个参数呢Q设x(chng)们用模?B>.*来匹配字W串"10,7,2"Q它应该匚w"10,"q是"10,7,"Qؓ(f)?jin)解册个两义性(ambiguityQ,正则表达式规定一律按照最长的串来Q在上面的例子中是"10,7,"Q显然这样就扑և?jin)两个参数而不是我们期望的一个。所以,我们要?B>[^,]*来强制取出第一个逗号之前的部分?/P>
q个表达式我们已l分析到?jin)?x)foo(\([^,]*\)Q这一D可以简单的译为“当你找?B>foo(把其后直到W一个逗号之前的部分标Cؓ(f)\1”。然后我们用同L(fng)办法标记W二个参Cؓ(f)\2。对W三个参数的标记Ҏ(gu)也是一P只是我们要搜索所有的字符直到x(chng)受我们ƈ没有必要L索第三个参数Q因为我们不需要调整它的位|,但是q样的模式能够保证我们只L换那些有三个参数的foo()Ҏ(gu)调用Q在foo()是一个重载(overoadingQ方法时q种明确的模式往往是比较保险的。然后,在替换部分,我们扑ֈfoo()的对应实例,然后利用标记好的部分q行替换Q是的第一和第二个参数交换位置?/P>
q里有几行我们现在的数据Q?/P>
下面是W一个替换命令:(x) 下面q个替换命o(h)则用来去除空|(x) 当然Q你也可以在Visual C++~辑器中使用RE。选择Edit->ReplaceQ然后选择"Regular expression"选择框,Find What输入框对应上面介l的vi命o(h):%s/pat1/pat2/g中的pat1部分Q而Replace输入框对应pat2部分。但是,Z(jin)得到vi的执行范围和g选项Q你要用Replace All或者适当的手工Find Next and ReplaceQ译者按Q知道ؓ(f)啥有人骂微Y弱智?jin)吧Q虽然VC中可以选中一个范围的文本Q然后在其中执行替换Q但是M不够vi那么灉|和典雅)(j)?/P>
Sed?B>Stream EDitor的羃写,是Unix下常用的Z文g和管道的~辑工具Q可以在手册中得到关于sed的详l信息? q里是一些有的sed脚本Q假定我们正在处理一个叫做price.txt的文件。注意这些编辑ƈ不会(x)改变源文Ӟsed只是处理源文件的每一行ƈ把结果显C在标准输出中(当然很容易用重定向来定Ӟ(j)Q?
he is a rat
我们可以使用grep命o(h)来测试我们的正则表达式,grep命o(h)使用正则表达式去试匚w指定文g的每一行,q将臛_有一处匹配表辑ּ的所有行昄出来。命?
he is in a rut
the food is Rotten
I like root beer grep r.t test.txt
在test.txt文g中的每一行中搜烦(ch)正则表达?B>r.tQƈ打印输出匚w的行。正则表辑ּr.t匚w一?B>r接着M一个字W再接着一?B>t。所以它?yu)匹配文件中?B>rat?B>rutQ而不能匹?B>Rotten中的RotQ因为正则表辑ּ是大写敏感的。要惛_时匹配大写和写字母Q应该用字W区间元字符Q方括号Q。正则表辑ּ[Rr]能够同时匚wR?B>r。所以,要想匚w一个大写或者小写的r接着M一个字W再接着一?B>tp使用q个表达式:(x)[Rr].t?
单的例子
vi 命o(h)
作用
:%s/ */ /g
把一个或者多个空格替换ؓ(f)一个空根{?/TD>
:%s/ *$//
L行尾的所有空根{?/TD>
:%s/^/ /
在每一行头上加入一个空根{?/TD>
:%s/^[0-9][0-9]* //
L行首的所有数字字W?/TD>
:%s/b[aeio]g/bug/g
所有的bag?I>beg?I>big?I>bog改ؓ(f)bug?nbsp;
:%s/t\([aou]\)g/h\1t/g
所?I>tag?I>tog?I>tug分别改ؓ(f)hat?I>hot?I>hugQ注意用group的用法和使用\1引用前面被匹配的字符Q?/TD>
中的例子(奇的咒语)(j)
?
之前
之后
foo(10,7,2)
foo(7,10,2)
foo(x+13,y-2,10)
foo(y-2,x+13,10)
foo( bar(8), x+y+z, 5)
foo( x+y+z, bar(8), 5) :%s/foo(\([^,]*\),\([^,]*\),\([^)]*\))/foo(\2,\1,\3)/g
[^,]
除了(jin)逗号之外的Q何字W?/TD>
[^,]*
0或者多个非逗号字符
\([^,]*\)
这些非逗号字符标记?B>\1Q这样可以在之后的替换模式表辑ּ中引用它
\([^,]*\),
我们必须扑ֈ0或者多个非逗号字符后面跟着一个逗号Qƈ且非逗号字符那部分要标记出来以备后用?/TD> ?
假设有一个CSVQcomma separated valueQ文Ӟ里面有一些我们需要的信息Q但是格式却有问题,目前数据的列序是:(x)姓名Q公司名Q州名羃写,邮政~码Q现在我们希望讲q些数据重新l织Q以便在我们的某个Y件中使用Q需要的格式为:(x)姓名Q州名羃?邮政~码Q公司名。也是_(d)我们要调整列序Q还要合q两个列来构成一个新列。另外,我们的Y件不能接受逗号前后面有MI格Q包括空格和制表W)(j)所以我们还必须要去掉逗号前后的所有空根{?
Bill Jones, HI-TEK Corporation , CA, 95011
我们希望把它变成q个样子Q?
Sharon Lee Smith, Design Works Incorporated, CA, 95012
B. Amos , Hill Street Cafe, CA, 95013
Alexander Weatherworth, The Crafts Store, CA, 95014
... Bill Jones,CA 95011,HI-TEK Corporation
我们用两个正则表达式来解决q个问题。第一个移动列和合q列Q第二个用来LI格?
Sharon Lee Smith,CA 95012,Design Works Incorporated
B. Amos,CA 95013,Hill Street Cafe
Alexander Weatherworth,CA 95014,The Crafts Store
... :%s/\([^,]*\),\([^,]*\),\([^,]*\),\(.*\)/\1,\3 \4,\2/
q里的方法跟?基本一PW一个列Q姓名)(j)用这个表辑ּ来匹配:(x)\([^,]*\)Q即W一个逗号之前的所有字W,而姓名内容被?B>\1标记下来。公司名和州名羃写字D는同样的方法标Cؓ(f)\2?B>\3Q而最后一个字D는\(.*\)来匹配("匚w所有字W直到行?Q。替换部分则引用上面标记的那些内Ҏ(gu)q行构造?
:%s/[ \t]*,[ \t]*/,/g
我们q是分解来看Q?B>[ \t]匚wI格/制表W,[ \t]* 匚w0或多个空?制表W,[ \t]*,匚w0或多个空?制表W后面再加一个逗号Q最后,[ \t]*,[ \t]*匚w0或多个空?制表W接着一个逗号再接着0或多个空?制表W。在替换部分Q我们简单的我们扑ֈ的所有东西替换成一个逗号。这里我们用了(jin)l尾的可选的g参数Q这表示在每行中Ҏ(gu)有匹配的串执行替换(而不是缺省的只替换第一个匹配串Q?
?
假设有一个多字符的片断重复出玎ͼ例如Q?
Billy tried really hard
而你x(chng)"really"?really really"Q以?qing)Q意数量连l出现的"really"字符串换成一个简单的"very"Qsimple is good!Q,那么以下命o(h)Q?
Sally tried really really hard
Timmy tried really really really hard
Johnny tried really really really really hard:%s/\(really \)\(really \)*/very /
׃(x)把上q的文本变成Q?
Billy tried very hard
表达?B>\(really \)*匚w0或多个连l的"really "Q注意结有个空|(j)Q?B>\(really \)\(really \)* 匚w1个或多个q箋(hu)?really "实例?
Sally tried very hard
Timmy tried very hard
Johnny tried very hard困难的例子(不可思议的象形文字)(j)
Coming soon.
不同工具中的正则表达?/H1>OKQ你已经准备使用REQregular expressionsQ正则表辑ּQ,但是你ƈ准备使用vi。所以,在这里我们给Z些在其他工具中用RE的例子。另外,我还?sh)(x)ȝ一下你在不同程序之间用RE可能发现的区别?
sed
sed脚本
描述
sed 's/^$/d' price.txt
删除所有空?/TD>
sed 's/^[ \t]*$/d' price.txt
删除所有只包含I格或者制表符的行
sed 's/"http://g' price.txt
删除所有引?/TD>
在AhoQW(xu)einberger和Kernighan的书The AWK Programming Language中有很多很好的awk的例子,请不要让下面q些微不道的脚本例子限制你对awk强大能力的理解。我们同样假定我们针对price.txt文gq行处理Q跟sed一Pawk也只是把l果昄在终端上?nbsp;
awk脚本 | 描述 | |
|
| |
awk '$0 !~ /^$/' price.txt | 删除所有空?/TD> | |
awk 'NF > 0' price.txt | awk中一个更好的删除所有行的办?/TD> | |
awk '$2 ~ /^[JT]/ {print $3}' price.txt | 打印所有第二个字段?J'或?T'打头的行中的W三个字D?/TD> | |
awk '$2 !~ /[Mm]isc/ {print $3 + $4}' price.txt | 针对所有第二个字段不包?Misc'或?misc'的行Q打印第3和第4列的和(假定为数字)(j) | |
awk '$3 !~ /^[0-9]+\.[0-9]*$/ {print $0}' price.txt | 打印所有第三个字段不是数字的行Q这里数字是?TT>d.d或?TT>dq样的Ş式,其中d??的Q何数?/TD> | |
awk '$2 ~ /John|Fred/ {print $0}' price.txt | 如果W二个字D包?John'或?Fred'则打印整?/TD> |
下面的例子中我们假定在文件phone.txt中包含以下的文本Q——其格式是姓加一个逗号Q然后是名,然后是一个制表符Q然后是?sh)话L(fng)Q?/P>
Francis, John 5-3871
Wong, Fred 4-4123
Jones, Thomas 1-4122
Salazar, Richard 5-2522
grep命o(h) | 描述 | |
|
| |
grep '\t5-...1' phone.txt | 把所有电(sh)话号码以5开头以1l束的行打印出来Q注意制表符是用\t表示?/TD> | |
grep '^S[^ ]* R' phone.txt | 打印所有姓以S打头和名以R打头的行 | |
grep '^[JW]' phone.txt | 打印所有姓开头是J或者W的行 | |
grep ', ....\t' phone.txt | 打印所有姓?个字W的行,注意制表W是?B>\t表示?/TD> | |
grep -v '^[JW]' phone.txt | 打印所有不以J或者W开头的?/TD> | |
grep '^[M-Z]' phone.txt | 打印所有姓的开头是M到Z之间M字符的行 | |
grep '^[M-Z].*[12]' phone.txt | 打印所有姓的开头是M到Z之间M字符Qƈ且点号号码结是1或?的行 |
egrep command | Description | |
|
| |
egrep '(John|Fred)' phone.txt | 打印所有包含名?I>John或?I>Fred的行 | |
egrep 'John|22$|^W' phone.txt | 打印所有包?I>John 或者以22l束或者以W的行 | |
egrep 'net(work)?s' report.txt | 从report.txt中找到所有包?I>networks或?I>nets的行 |
命o(h)或环?/B> | . | [ ] | ^ | $ | \( \) | \{ \} | ? | + | | | ( ) |
vi | X | X | X | X | X | |||||
Visual C++ | X | X | X | X | X | |||||
awk | X | X | X | X | X | X | X | X | ||
sed | X | X | X | X | X | X | ||||
Tcl | X | X | X | X | X | X | X | X | X | |
ex | X | X | X | X | X | X | ||||
grep | X | X | X | X | X | X | ||||
egrep | X | X | X | X | X | X | X | X | X | |
fgrep | X | X | X | X | X | |||||
perl | X | X | X | X | X | X | X | X | X |
s 表示其后是一个替换命令?/P>
pat1 q是要查扄一个正则表辑ּQ这文章中有一大堆例子?/P>
g 可选标志,带这个标志表C替换将针对行中每个匚w的串q行Q否则则只替换行中第一个匹配串?/P>
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); String url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl为数据库的SID String user="test"; String password="test"; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance(); String url="jdbc:db2://localhost:5000/sample"; //sampleZ的数据库? String user="admin"; String password=""; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb"; //mydb为数据库 String user="sa"; String password=""; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("com.sybase.jdbc.SybDriver").newInstance(); String url =" jdbc:sybase:Tds:localhost:5007/myDB";//myDBZ的数据库? Properties sysProps = System.getProperties(); SysProps.put("user","userid"); SysProps.put("password","user_password"); Connection conn= DriverManager.getConnection(url, SysProps); |
Class.forName("com.informix.jdbc.IfxDriver").newInstance(); String url = "jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver; user=testuser;password=testpassword"; //myDB为数据库? Connection conn= DriverManager.getConnection(url); |
Class.forName("org.gjt.mm.mysql.Driver").newInstance(); String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1" //myDB为数据库? Connection conn= DriverManager.getConnection(url); |
Class.forName("org.postgresql.Driver").newInstance(); String url ="jdbc:postgresql://localhost/myDB" //myDB为数据库? String user="myuser"; String password="mypassword"; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ; String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/ReportDemo.mdb"); Connection conn = DriverManager.getConnection(url,"",""); Statement stmtNew=conn.createStatement() ; |
try{ Class.forName(com.mysql.jdbc.Driver); System.out.println(Success loading Mysql Driver!); }catch(Exception e) { System.out.println(Error loading Mysql Driver!); e.printStackTrace(); } |
jdbcQmysqlQ?/localhost/databasename[?pa=va][Qpa=va] |
PreparedStatement pstmt3D null; try { ((OraclePreparedStatement)pstmt).setExecuteBatch(30); ... pstmt.executeUpdate(); } |
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFCell; import java.io.FileOutputStream; public class CreateXL { /** Excel 文g要存攄位置Q假定在D盘JTest目录?/ public static String outputFile="D:/JTest/ gongye.xls"; public static void main(String argv[]){ try{ // 创徏新的Excel 工作?BR> HSSFWorkbook workbook = new HSSFWorkbook(); // 在Excel工作中Z工作表,其名为缺省?BR> // 如要新徏一名ؓ(f)"效益指标"的工作表Q其语句为:(x) // HSSFSheet sheet = workbook.createSheet("效益指标"); HSSFSheet sheet = workbook.createSheet(); // 在烦(ch)?的位|创Q最端的行Q?BR> HSSFRow row = sheet.createRow((short)0); //在烦(ch)?的位|创建单元格Q左上端Q?BR> HSSFCell cell = row.createCell((short) 0); // 定义单元gؓ(f)字符串类?BR> cell.setCellType(HSSFCell.CELL_TYPE_STRING); // 在单元格中输入一些内?BR> cell.setCellValue("增加?); // 新徏一输出文g?BR> FileOutputStream fOut = new FileOutputStream(outputFile); // 把相应的Excel 工作存?BR> workbook.write(fOut); fOut.flush(); // 操作l束Q关闭文?BR> fOut.close(); System.out.println("文g生成..."); }catch(Exception e) { System.out.println("已运?xlCreate() : " + e ); } } } |
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFCell; import java.io.FileInputStream; public class ReadXL { /** Excel文g的存放位|。注意是正斜U?/ public static String fileToBeRead="D:/JTest/ gongye.xls"; public static void main(String argv[]){ try{ // 创徏对Excel工作文件的引用 HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead)); // 创徏对工作表的引用?BR> // 本例是按名引用(让我们假定那张表有着~省?Sheet1"Q?BR> HSSFSheet sheet = workbook.getSheet("Sheet1"); // 也可用getSheetAt(int index)按烦(ch)引引用, // 在Excel文档中,W一张工作表的缺省烦(ch)引是0Q?BR> // 其语句ؓ(f)QHSSFSheet sheet = workbook.getSheetAt(0); // d左上端单?BR> HSSFRow row = sheet.getRow(0); HSSFCell cell = row.getCell((short)0); // 输出单元内容Qcell.getStringCellValue()是取所在单元的?BR> System.out.println("左上端单元是Q?" + cell.getStringCellValue()); }catch(Exception e) { System.out.println("已运行xlRead() : " + e ); } } } |
HSSFFont font = workbook.createFont(); font.setColor(HSSFFont.COLOR_RED); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); |
HSSFCellStyle cellStyle= workbook.createCellStyle(); cellStyle.setFont(font); |
HSSFCell cell = row.createCell((short) 0); cell.setCellStyle(cellStyle); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue("标题 "); |