您的位置:首页 > 其它

字符串操作(2)---使用正则表达式

2007-02-14 15:21 288 查看
/*********************************************
*Author:Java619
*Time:2007-02-14
**********************************************/

本文继续字符串操作(1)中的问题(从"aab${aaa}esfd${bb}1c${cccc}132${dds}"中分离出aaa,bb,dds),这次将使用正则表达式,以使上一例子更通用.本例用于了Jakarta ORO 包(点击下载或到apache官方网下载).关于正表达式的介绍大家可以去看"仙人掌工作室"中的介绍,里面已经说得很祥细.

要从"aab${aaa}esfd${bb}1c${cccc}132${dds}"中分离出aaa,bb,dds可以这样实现

import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Pattern;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.oro.text.regex.MatchResult;
public class RegularExpress3
{
/**
*从"aab${aaa}esfd${bb}1c${cccc}132${dds}"中分离出
*aaa,bb,cccc,dds
*@author java619
*/
public static void main(String[] args)
{
String str="aab${aaa}esfd${bb}1c${cccc}132${dds}";
////$ 使用转意符表示$ 注意由于BLOG显示问题,记得是两个"/"
////{ //} 使用转意符表示{ } 注意"{","}"在正则表达式中是有特殊意义的
//所以应用"/{"加以区分,而第一个"/"用天告诉Java其后要表示一"/"
String regexp="//$//{([^//}]+)//}";
try{
PatternCompiler compile=new Perl5Compiler();
Pattern pattern=compile.compile(regexp);
PatternMatcher matcher=new Perl5Matcher();
PatternMatcherInput input=new PatternMatcherInput(str);
while(matcher.contains(input,pattern)){
MatchResult result=matcher.getMatch();
System.out.println(result.group(1));
}
}catch(Exception e){
System.out.println(e.toString());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: