[英]Soapui - Groovy ReplaceAll regex
我有一個字符串 (myString),其中包含一些 xml 標簽,例如...
<TargetValue>4</TargetValue>
<TargetValue></TargetValue>
<TargetValue>2</TargetValue>
我需要用我使用代碼生成的隨機數替換標簽之間的所有數字
def myRnd = Math.abs(new Random().nextInt() % 10) + 1
我嘗試了各種 replaceAll 命令,但似乎無法使正則表達式正確,因為沒有任何東西被替換。 有人知道如何構造正確的 replaceAll 命令來更新標簽之間的所有值嗎
謝謝
嘗試:
def str = '''<TargetValue>4</TargetValue>
<TargetValue></TargetValue>
<TargetValue>2</TargetValue>
'''
str.replaceAll(/[0-9]+/) {
Math.abs(new Random().nextInt() % 10) + 1
}
更新
然后嘗試類似:
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 需要一個根節點格式良好。 然后,您可以使用XmlSlurper
執行與使用正則表達式相同的操作:
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)
此腳本記錄:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<TargetValue>8</TargetValue>
<TargetValue>3</TargetValue>
<TargetValue>6</TargetValue>
</root>
希望能幫助到你,
這對你有用嗎:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.