替换正则表达式字符

时间:2014-01-15 11:15:48

标签: java regex substring

我想将子字符串\\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)));

但它不起作用。

2 个答案:

答案 0 :(得分: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);

<强>更新 之前的代码是用不同的随机数替换每个出现的,如果你想用THE SAME替换所有出现的随机数,请使用:

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);
}

答案 1 :(得分:0)

您需要使用Matcher#ewplaceAll(String replacement)

Pattern p1 = Pattern.compile("\\d+-\\d+");
Matcher m = p1.matcher(INPUT);
INPUT = m.replaceAll( String.valueOf(randomInt) );