【问题标题】:Soapui - Groovy ReplaceAll regexSoapui - Groovy ReplaceAll 正则表达式
【发布时间】:2015-11-05 10:39:01
【问题描述】:

我有一个字符串 (myString),其中包含一些 xml 标签,例如...

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

我需要用我使用代码生成的随机数替换标签之间的所有数字

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

我尝试了各种 replaceAll 命令,但似乎无法正确使用正则表达式,因为没有任何东西被替换。有人知道如何构造正确的 replaceAll 命令来更新标签之间的所有值

谢谢

【问题讨论】:

  • 您不应该使用正则表达式解析 XML。查看 XmlSlurper 或 XmlParser

标签: regex groovy soapui


【解决方案1】:

尝试:

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>

希望对你有帮助,

【讨论】:

  • 对不起,我应该很清楚。 XML 还将包含其他可能有数字的标签,所以我只想更改 TargetValue 标签中的值,而不是 xml 中的每个数字
  • 谢谢,非常接近。它还需要更新不包含数字的 TargetValue 标签
  • @user3803807 所有 标签,尽管它们的内容?
【解决方案2】:

这对你有用吗:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多