正则表达式



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; iSystem.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)

相关资讯

  • ·Eclipse快捷键
  • 快速服务服务:网站策划 | 网站建设 | 北京网站建设 | 网站推广 | 网罗SEO
  • 联系网罗: 咨询电话:010-89630319 Mail:admin#wonlu.com Msn:刘先生 QQ:26402294
  •   2006-2008 Wonlu.com 北京网罗无限-京ICP备06036090号 网罗SEO