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

本文介绍如何使用Jakarta ORO包和正则表达式从特定格式的字符串中提取所需内容,通过实例演示了从含有特殊符号的字符串中提取指定部分的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*********************************************
*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());
  }
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值