我的程序员生涯(2006)
benq · benq() · 2004-04-10
我的程序员生涯(2006)
2006 新起点,新收获......期待更多的幸福
<< Java和Jsp 学习心得
|
首页
|
JBUILDER X+Weblogic8.1+SQL Server2000两种数据库连接方法 >>
正则表达式和Java编程语言
时间: 2004年04月10日
类和方法
下面的类根据正则表达式指定的模式,与字符序列进行匹配。
Pattern类
Pattern
类的实例表示以字符串形式指定的正则表达式,其语 法类似于Perl所用的语法。
用字符串形式指定的正则表达式,必须先编译成
Pattern
类的 实例。生成的模式用于创建
Matcher
对象,它根据正则表达式与任 意字符序列进行匹配。多个匹配器可以共享一个模式,因为它是非专属的。
用
compile
方法把给定的正则表达式编译成模式,然后用
matcher
方法创建一个匹配器,这个匹配器将根据此模式对给定输 入进行匹配。
pattern
方法可返回编译这个模式所用的正则表达 式。
split
方法是一种方便的方法,它在与此模式匹配的位置将给 定输入序列切分开。下面的例子演示了:
/*
* 用split对以逗号和/或空格分隔的输入字符串进行切分。
*/
import java.util.regex.*;
public class Splitter {
public static void main(String[] args) throws Exception {
// Create a pattern to match breaks
Pattern p = Pattern.compile("[,\\s]+");
// Split input with the pattern
String[] result =
p.split("one,two, three four , five");
for (int i=0; i<result.length; i++)
System.out.println(result[i]);
}
}
Matcher类
Matcher
类的实例用于根据给定的字符串序列模式,对字符序 列进行匹配。使用
CharSequence
接口把输入提供给匹配器,以便 支持来自多种多样输入源的字符的匹配。
通过调用某个模式的
matcher
方法,从这个模式生成匹配器。 匹配器创建之后,就可以用它来执行三类不同的匹配操作:
matches
方法试图根据此模式,对整个输入序列进行匹配。
lookingAt
方法试图根据此模式,从开始处对输入序列进 行匹配。
find
方法将扫描输入序列,寻找下一个与模式匹配的地方。
这些方法都会返回一个表示成功或失败的布尔值。如果匹配成功,通过查询 匹配器的状态,可以获得更多的信息
这个类还定义了用新字符串替换匹配序列的方法,这些字符串的内容如果需 要的话,可以从匹配结果推算得出。
appendReplacement
方法先添加字符串中从当前位置到下一个 匹配位置之间的所有字符,然后添加替换值。
appendTail
添加的 是字符串中从最后一次匹配的位置之后开始,直到结尾的部分。
例如,在字符串
blahcatblahcatblah
中,第一个
appendReplacement
添加
blahdog
。第二个
appendReplacement
添加
blahdog
,然后
appendTail
添加
blah
,就生成了:
blahdogblahdogblah
。请参见示例
简单的单词替换
。
CharSequence接口
CharSequence
接口为许多不同类型的字符序列提供了统一的只 读访问。你提供要从不同来源搜索的数据。用
String, StringBuffer
和
CharBuffer
实现
CharSequence,
,这样就可以很 容易地从它们那里获得要搜索的数据。如果这些可用数据源没一个合适的,你可 以通过实现
CharSequence
接口,编写你自己的输入源。
Regex情景范例
以下代码范例演示了
java.util.regex
软件包在各种常见情形 下的用法:
简单的单词替换
/*
* This code writes "One dog, two dogs in the yard."
* to the standard-output stream:
*/
import java.util.regex.*;
public class Replacement {
public static void main(String[] args)
throws Exception {
// Create a pattern to match cat
Pattern p = Pattern.compile("cat");
// Create a matcher with an input string
Matcher m = p.matcher("one cat," +
" two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
// Loop through and create a new String
// with the replacements
while(result) {
m.appendReplacement(sb, "dog");
result = m.find();
}
// Add the last segment of input to
// the new String
m.appendTail(sb);
System.out.println(sb.toString());
}
}
电子邮件确认
以下代码是这样一个例子:你可以检查一些字符是不是一个电子邮件地址。 它并不是一个完整的、适用于所有可能情形的电子邮件确认程序,但是可以在 需要时加上它。
/*
* Checks for invalid characters
* in email addresses
*/
public class EmailValidation {
public static void main(String[] args)
throws Exception {
String input = "@sun.com";
//Checks for email addresses starting with
//inappropriate symbols like dots or @ signs.
Pattern p = Pattern.compile("^\\.|^\\@");
Matcher m = p.matcher(input);
if (m.find())
System.err.println("Email addresses don't start" +
" with dots or @ signs.");
//Checks for email addresses that start with
//www. and prints a message if it does.
p = Pattern.compile("^www\\.");
m = p.matcher(input);
if (m.find()) {
System.out.println("Email addresses don't start" +
" with \"www.\", only web pages do.");
}
p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
m = p.matcher(input);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
boolean deletedIllegalChars = false;
while(result) {
deletedIllegalChars = true;
m.appendReplacement(sb, "");
result = m.find();
}
// Add the last segment of input to the new String
m.appendTail(sb);
input = sb.toString();
if (deletedIllegalChars) {
System.out.println("It contained incorrect characters" +
" , such as spaces or commas.");
}
}
}
从文件中删除控制字符
/* This class removes control characters from a named
* file.
*/
import java.util.regex.*;
import java.io.*;
public class Control {
public static void main(String[] args)
throws Exception {
//Create a file object with the file name
//in the argument:
File fin = new File("fileName1");
File fout = new File("fileName2");
//Open and input and output stream
FileInputStream fis =
new FileInputStream(fin);
FileOutputStream fos =
new FileOutputStream(fout);
BufferedReader in = new BufferedReader(
new InputStreamReader(fis));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(fos));
// The pattern matches control characters
Pattern p = Pattern.compile("{cntrl}");
Matcher m = p.matcher("");
String aLine = null;
while((aLine = in.readLine()) != null) {
m.reset(aLine);
//Replaces control characters with an empty
//string.
String result = m.replaceAll("");
out.write(result);
out.newLine();
}
in.close();
out.close();
}
}
文件查找
/*
* Prints out the comments found in a .java file.
*/
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
public class CharBufferExample {
public static void main(String[] args) throws Exception {
// Create a pattern to match comments
Pattern p =
Pattern.compile("//.*$", Pattern.MULTILINE);
// Get a Channel for the source file
File f = new File("
Replacement.java
");
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
// Get a CharBuffer from the source file
ByteBuffer bb =
fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
Charset cs = Charset.forName("8859_1");
CharsetDecoder cd = cs.newDecoder();
CharBuffer cb = cd.decode(bb);
// Run some matches
Matcher m = p.matcher(cb);
while (m.find())
System.out.println("Found comment: "+m.group());
}
}
结论
现在Java编程语言中的模式匹配和许多其他编程语言一样灵活了。可以在应 用程序中使用正则表达式,确保数据在输入数据库或发送给应用程序其他部分之 前,格式是正确的,正则表达式还可以用于各种各样的管理性工作。简而言之, 在Java编程中,可以在任何需要模式匹配的地方使用正则表达式。
benq()
引用(Trackback0)
评论
发表评论
最后更新
原始快照:web.archive.org