首页 > 安全资讯 >

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

11-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('${session.user.username}','${session.user.password}');\" >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('123','123');" >linkme</a>

作者“penggle”
 

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