java正則表達式分析替換字符串 – JAVA編程語言程序開發技術文章

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”
 

發佈留言