2014-01-15 245 views
0

我想將字符串\\d+-\\d+替換爲此字符串<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>\\d+-\\d+</tns:idValue中隨機指定的數字。替換正則表達式

我使用下面的代碼

String REGEXSIEBEL = "<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>\\d+-\\d+</tns:idValue>"; 
java.util.regex.Pattern p1 = java.util.regex.Pattern.compile(REGEXSIEBEL); 
java.util.regex.Matcher m = p1.matcher(INPUT); 

INPUT = m.replaceAll(REGEXSIEBEL.replaceAll(String.valueOf("\\d+-\\d+"), String.valueOf(randomInt))); 

但它不工作。

+1

你可以給一個樣品的輸入和輸出? – nhahtdh

回答

0

可以使用http://regex101.com/驗證您的正則表達式快速在線,也許你還可以檢查Java的正則表達式本教程以備將來參考:http://www.tutorialspoint.com/java/java_regular_expressions.htm

下面你手邊有一個全面實施的任務:

String str = "<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>84678468-00</tns:idValue>"; 
String patternString = "<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>\\d{8}-00<\\/tns:idValue>"; 
Pattern pattern = Pattern.compile(patternString); 
Matcher matcher = pattern.matcher(str); 

StringBuffer sb = new StringBuffer(); 

while(matcher.find()){ 
    String randomNumberTag = "<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>"+ 
     Integer.toString((int)(Math.random() * 99999999)) 
     +"-00</tns:idValue>"; 
    matcher.appendReplacement(sb,randomNumberTag); 
} 
matcher.appendTail(sb); 

更新 以前的代碼旨在用不同的隨機數替換每個發生的事件,如果您希望所有事件都被替換爲相同的隨機數,請使用:

String str = "<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>84678468-00</tns:idValue>"; 
String patternString = "<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>\\d{8}-00<\\/tns:idValue>"; 
Pattern pattern = Pattern.compile(patternString); 
Matcher matcher = pattern.matcher(str); 

String randomNumberTag = "<!-- This is Siebel Order identified --> <tns:id> <tns:idValue>"+ 
    Integer.toString((int)(Math.random() * 99999999)) 
      +"-00</tns:idValue>"; 
System.out.println(randomNumberTag); 
if(matcher.find()){ 
    str = matcher.replaceAll(randomNumberTag); 
}