shaa0601
shaa0601

Reputation: 111

Regular Expression for SOAP Response in Groovy

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=&quot;&quot; ImageFile=&quot;&quot; LocaleCode=&quot;en_US_EST&quot;
    UserToken=&quot;bb14MY&quot;
</loginReturn></p561:loginResponse></soapenv:Body></soapenv:Envelope>

Upvotes: 0

Views: 771

Answers (3)

cfrick
cfrick

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=&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"

Upvotes: 0

shaa0601
shaa0601

Reputation: 111

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

This is what I did to solve my question.

Upvotes: 0

Amen Jlili
Amen Jlili

Reputation: 1944

Use the following pattern to get your usertoken. I'm using a capturing group to get it.

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

Demo here.

Needless to say, your regex object must handle multilines.

Upvotes: 1

Related Questions