2015-11-05 68 views
-2

我有一个字符串(MyString的),其中包含一些XML标记,如...SOAPUI - Groovy的正则表达式的replaceAll

<TargetValue>4</TargetValue> 
<TargetValue></TargetValue> 
<TargetValue>2</TargetValue> 

我需要一个随机数,以取代所有的标签之间的数字使用代码生成我

def myRnd = Math.abs(new Random().nextInt() % 10) + 1 

我已经尝试了各种的replaceAll的命令,但似乎无法得到正确的正则表达式作为从来都没有被替换。会有人知道如何构建正确的replaceAll命令标签之间更新所有的值

感谢

+1

shoul You不要用正则表达式解析XML。看看XmlSlurper或XmlParser –

回答

1

尝试用:

def str = '''<TargetValue>4</TargetValue> 
<TargetValue></TargetValue> 
<TargetValue>2</TargetValue> 
''' 

str.replaceAll(/[0-9]+/) { 
    Math.abs(new Random().nextInt() % 10) + 1 
} 

UPDATE

然后尝试类似:

def str = '''<TargetValue>4</TargetValue> 
<TargetValue></TargetValue> 
<TargetValue>2</TargetValue> 
''' 

str.replaceAll(/\<TargetValue\>\d+\<\/TargetValue\>/) { 
    '<TargetValue>' + (Math.abs(new Random().nextInt() % 10) + 1) + '</TargetValue>' 
} 

更新2

由于@tim_yates建议,最好使用XmlSlurper比正则表达式,但你需要一个良好的XML解析,所以在你的例子你的XML需要一个根节点得到很好的形成。

def str = '''<root> 
<TargetValue>4</TargetValue> 
<TargetValue></TargetValue> 
<TargetValue>2</TargetValue> 
</root> 
''' 

def xml = new XmlSlurper().parseText(str) 
xml.'**'.findAll { 
    it.name() == 'TargetValue' 
}.each { 
    it.replaceBody(Math.abs(new Random().nextInt() % 10) + 1) 
} 

println XmlUtil.serialize(xml) 

这个脚本日志:然后,你可以为你使用正则表达式使用XmlSlurper做同样的

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <TargetValue>8</TargetValue> 
    <TargetValue>3</TargetValue> 
    <TargetValue>6</TargetValue> 
</root> 

希望它能帮助,

+0

对不起,我应该清楚。 XML中还会包含其他可能有数字的标签,所以我特别只想更改TargetValue标签中的值而不是xml中的每个数字 – user3803807

+0

@ user3803807 updated':)' – albciff

+0

非常接近。它还需要更新不包含 – user3803807

0

这是否会为你工作:

String ss = "<TargetValue>4</TargetValue>"; 
int myRnd = Math.abs(new Random().nextInt() % 10) + 1; 
String replaceAll = ss.replaceAll("\\<TargetValue\\>\\d+\\</TargetValue+\\>", "<TargetValue>"+myRnd+"</TargetValue>", String.valueOf(myRnd)); 
System.out.println(replaceAll);