Soapui - Groovy ReplaceAll 正则表达式

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

As @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>

希望对您有所帮助,

Will this work for you:

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