Topic: 求一算法(正则表达)

  Print this page

1.求一算法(正则表达) Copy to clipboard
Posted by: athlon
Posted on: 2005-09-28 20:52

有这样一个串 ('/images/top_menu01b.gif','/images/top_menu02b.gif','/images/top_menu03b.gif','/images/top_menu04b.gif','/images/top_menu05b.gif','/images/top_menu06b.gif','/images/top_menu07b.gif','/images/top_menu08b.gif','/images/top_menu09b.gif','/images/top_menu10b.gif','/images/top_menu11b.gif','/images/top_menu12b.gif','/images/top_menu13b.gif','/images/top_menu14b.gif','/images/index_img/l_more1b.gif','/images/index_img/l_more2b.gif','/images/index_img/m1more2.gif','/images/jinshu/r_more1b.gif','/images/jinshu/r_more3b.gif')"
现在需要在images前面加一个串,如:'/aaa/images/top_menu01b.gif';
我想用正则表达试去实现替换,不知怎么实现?望高手帮忙解答一下,谢谢先。

2.Re:求一算法(正则表达) [Re: athlon] Copy to clipboard
Posted by: why
Posted on: 2005-09-28 22:15

It's a constant pattern?
What are you concerns?Question

  public static void main(String[] args) {
    String inStr = "('/images/top_menu01b.gif','/images/jinshu/r_more3b.gif')";
    String patternStr = "/images/";
    String replacementStr = "/aaa/images/";

    Pattern pattern = Pattern.compile(patternStr);

    Matcher matcher = pattern.matcher(inStr);
    String outStr = matcher.replaceAll(replacementStr);

    System.out.println(outStr);
  }


or simply
java.util.regex.Pattern.compile(patternStr).matcher(inStr).replaceAllreplacementStr);

or just use String's replaceAll
inStr.replaceAll(patternStr, replacementStr);

or the replaceAll of org.apache.commons.lang.StringUtils

3.Re:求一算法(正则表达) [Re: athlon] Copy to clipboard
Posted by: athlon
Posted on: 2005-09-29 17:15

我在网上看个一篇文章是关于正则表达式的替换方法,用的是Util.substitute()方法,地址:http://www.51cto.com/html/2005/0915/3118.htm ,结合这篇文章我写了一个方法,现贴出来,让大家看看:
/**
* @param source 源字符串
* @param reg 正则表达式 "/(/*\\-*\\w)*?\\.gif"
* @param dir 需要加的字符串
* @return
*/
static String replace(String source,String reg,String dir)
{
String changestring = "";

String numberExpression = "("+reg+")";

Pattern pattern = null;

PatternCompiler compiler;

PatternMatcher matcher;

MatchResult result;

// Create Perl5Compiler and Perl5Matcher instances.
compiler = new Perl5Compiler();

matcher = new Perl5Matcher();

try {
pattern = compiler.compile(numberExpression);
} catch(MalformedPatternException e) {

}
Perl5Substitution p5s = new Perl5Substitution( dir+"$1",0);

changestring = Util.substitute(matcher,pattern,p5s,source,Util.SUBSTITUTE_ALL);

System.out.println("test:"+changestring);

return changestring;
}
用的包是jakarta-oro-2.0.8.jar,有不足之处望大家指出;非常感谢why,给我的提示;


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923