我是否在使用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="" ImageFile="" LocaleCode="en_US_EST"
UserToken="bb14MY"
</loginReturn></p561:loginResponse></soapenv:Body></soapenv:Envelope>
答案 0 :(得分:1)
答案 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="" ImageFile="" LocaleCode="en_US_EST"
UserToken="bb14MY"
</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="(.*?)"/
matcher = soap =~ pattern
assert matcher
assert matcher.group(1)=="bb14MY"
// or use `Pattern.MULTILINE` (`(?m)`) with your `^\s*`:
pattern = /(?m)^\s*UserToken="(.*?)"/
matcher = soap =~ pattern
assert matcher
assert matcher.group(1)=="bb14MY"
答案 2 :(得分:0)
def soapResponse = connection.content.text;
Pattern pattern = Pattern.compile(/(?s)UserToken="(.*?)"/, Pattern.DOTALL);
Matcher matcher = pattern.matcher(soapResponse);
if (matcher.find()) {
println(matcher.group(1));
}
这就是我解决问题的方法。