??
/********************************************* *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,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,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()); } } } (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|