java中正则表达式

什麼是正規表示式呢(Reqular Expressions)

就是針對檔案、字串,透過一種很特別的表示式來作search與replace

因為在unix上有很多系統設定都是存放在文字檔中,因此網管或程式設計常常需要作搜尋與取代

所以發展出一種特殊的命令叫做正規表示式

我們可以很簡單的用 "s/

因此jdk1.4提供了一組正規表示式的package供大家使用

若是jdk1.4以下的可以到http://jakarta.apache.org/oro取得相關功能的package

剛剛列出的一串符號" s/

適用於j2sdk1.4的正規語法

"." 代表任何字元

正規式 原字串 符合之字串
. ab a
.. abc ab

"+" 代表一個或以個以上的字元
"*" 代表零個或是零個以上的字元

正規式 原字串 符合之字串
+ ab ab
* abc abc

"( )"群組

正規式 原字串 符合之字串
(ab)* aabab abab

字元類

正規式 原字串 符合之字串
[a-dA-D0-9]* abczA0 abcA0
[^a-d]* abe0 e0
[a-d]* abcdefgh abab


簡式

\d 等於 [0-9] 數字
\D 等於 [^0-9] 非數字
\s 等於 [ \t\n\x0B\f\r] 空白字元
\S 等於 [^ \t\n\x0B\f\r] 非空白字元
\w 等於 [a-zA-Z_0-9] 數字或是英文字
\W 等於 [^a-zA-Z_0-9] 非數字與英文字

每一行的開頭或結尾

^ 表示每行的開頭
$ 表示每行的結尾

--------------------------------------------------------------------------------

正規表示式 java.util.regex 相關的類別

 Pattern—正規表示式的類別
 Matcher—經過正規化的結果
 PatternSyntaxExpression—Exception thrown while attempting to compile a regular expression

範例1: 將字串中所有符合"<"的字元取代成"lt;"

import java.io.*;
import java.util.regex.*;
/**
* 將字串中所有符合"<"的字元取代成"lt;"
*/
public static void replace01(){
// BufferedReader lets us read line-by-line
Reader r = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader( r );
Pattern pattern = Pattern.compile( "<" ); // 搜尋某字串所有符合'<'的字元
try{
while (true) {
String line = br.readLine();
// Null line means input is exhausted
if (line==null)
break;
Matcher a = pattern.matcher(line);
while(a.find()){
System.out.println("搜尋到的字元是" + a.group());
}
System.out.println(a.replaceAll("lt;"));// 將所有符合字元取代成lt;
}
}catch(Exception ex){ex.printStackTrace();};
}

範例2:

import java.io.*;
import java.util.regex.*;
/**
* 類似StringTokenizer的功能
* 將字串以","分隔然後比對哪個token最長
*/
public static void search01(){
// BufferedReader lets us read line-by-line
Reader r = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader( r );
Pattern pattern = Pattern.compile( ",\\s*" );// 搜尋某字串所有","的字元
try{
while (true) {
String line = br.readLine();
String words[] = pattern.split(line);
// Null line means input is exhausted
if (line==null)
break;
// -1 means we haven't found a word yet
int longest=-1;
int longestLength=0;
for (int i=0; i System.out.println("分段:" + words[i] );
if (words[i].length() > longestLength) {
longest = i;
longestLength = words[i].length();
}
}
System.out.println( "長度最長為:" + words[longest] );
}
}catch(Exception ex){ex.printStackTrace();};
}

--------------------------------------------------------------------------------

其他的正規語法

/^\s* # 忽略每行開始的空白字元
(M(s|r|rs)\.) # 符合 Ms., Mrs., and Mr. (titles)

**********************************************

下面的类根据正则表达式指定的模式,与字符序列进行匹配。

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 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编程中,可以在任何需要模式匹配的地方使用正则表达式。

posted on 2006-08-08 22:00 穷鬼 阅读(326) 评论(0)  编辑  收藏 所属分类: Java 基础

只有注册用户登录后才能发表评论。


网站导航: