Groovy中SOAP响应的正则表达式

时间:2015-02-16 20:47:38

标签: regex soap groovy

我是否在使用Groovy中的正则表达式匹配/提取UserToken(即“bb14MY”)的值时做错了什么?

@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.0')
import wslite.soap.*
import wslite.http.auth.*
import java.util.regex.*      
import groovy.xml.*
import groovy.util.*
import java.lang.*

...
...
...

def soapResponse = connection.content.text;

String str = println "$soapResponse";

Pattern pattern = Pattern.compile("^\\s*UserToken="(.*?)"", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
          println(matcher.group(1));
}

$ soapResponse的输出如下所示。

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    ContactAddress_Key=&quot;&quot; ImageFile=&quot;&quot; LocaleCode=&quot;en_US_EST&quot;
    UserToken=&quot;bb14MY&quot;
</loginReturn></p561:loginResponse></soapenv:Body></soapenv:Envelope>

3 个答案:

答案 0 :(得分:1)

使用以下模式获取您的使用权。我正在使用捕获组来获取它。

UserToken=.+;(\w+).+;

演示here

毋庸置疑,您的正则表达式对象必须处理多行。

答案 1 :(得分:0)

在这里使用^是错误的,因为DOTALL只会使常规字符串的换行符匹配。我想你想要MULTILINE,但它也可以在没有它的情况下运行。 E.g。

def soap="""\
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    ContactAddress_Key=&quot;&quot; ImageFile=&quot;&quot; LocaleCode=&quot;en_US_EST&quot;
    UserToken=&quot;bb14MY&quot;
</loginReturn></p561:loginResponse></soapenv:Body></soapenv:Envelope>"""
def pattern
def matcher

// stick with `Pattern.DOTALL` (`(?s)`), but get rid of handling for the start of the line:
pattern = /(?s)UserToken=&quot;(.*?)&quot;/
matcher = soap =~ pattern
assert matcher
assert matcher.group(1)=="bb14MY"

// or use `Pattern.MULTILINE` (`(?m)`) with your `^\s*`:
pattern = /(?m)^\s*UserToken=&quot;(.*?)&quot;/
matcher = soap =~ pattern
assert matcher
assert matcher.group(1)=="bb14MY"

答案 2 :(得分:0)

def soapResponse = connection.content.text;

Pattern pattern = Pattern.compile(/(?s)UserToken=&quot;(.*?)&quot;/, Pattern.DOTALL);
Matcher matcher = pattern.matcher(soapResponse);
if (matcher.find()) {
          println(matcher.group(1));
}

这就是我解决问题的方法。