首页 > 程序开发 > 软件开发 > Java >

java正则表达式分析替换字符串

2011-09-02

Java代码public static void main(String[] args){ String regex = "

Java代码
public static void main(String[] args){

String regex = "\\$\\{(.+?)\\}";
String str = "<a onclick=\"showUserName(&#39;${session.user.username}&#39;,&#39;${session.user.password}&#39;);\" >linkme</a>" ;
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
System.out.println(">>>>> replace sequence : " + matcher.group(0));
System.out.println(">>>>> index range : (" + matcher.start() + ", " + matcher.end() + ")");
System.out.println(">>>>> sub : " + str.substring(matcher.start(), matcher.end()));
matcher.appendReplacement(sb, "123");
System.out.println("-----------------");
}
matcher.appendTail(sb);
System.out.println(">>>> sb : " + sb.toString());

}

输出:

\$\{(.+?)\}
>>>>> replace sequence : ${session.user.username}
>>>>> index range : (26, 50)
>>>>> sub : ${session.user.username}
-----------------
>>>>> replace sequence : ${session.user.password}
>>>>> index range : (53, 77)
>>>>> sub : ${session.user.password}
-----------------
>>>> sb : <a onclick="showUserName(&#39;123&#39;,&#39;123&#39;);" >linkme</a>

作者“penggle”

相关文章
最新文章
热点推荐