2015-11-05 65 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);