Reputation: 111
Did I do something wrong here on matching/extracting the value of UserToken (ie. "bb14MY") using Regular Expression in Groovy??
@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));
}
The output of $soapResponse looks like below.
<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>
Upvotes: 0
Views: 771
Reputation: 37073
Using ^
here is wrong, as DOTALL just makes the linebreak match for a regular char. I think you want MULTILINE, but it also just works without it. 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"
Upvotes: 0
Reputation: 111
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));
}
This is what I did to solve my question.
Upvotes: 0
Reputation: 1944
Use the following pattern to get your usertoken. I'm using a capturing group to get it.
UserToken=.+;(\w+).+;
Needless to say, your regex object must handle multilines.
Upvotes: 1