Question

I have a the following string:

Source: "HKID:A1234567~PKey:00888880~DOC:TKWC033330"

Regex:  .*(HKID:.*?)(.+?)((?=~)|\s|\z)

When I test this at the JavaScript Regular Expression Test site I got A1234567 so all are good.

I put this expression in a javascript transformer in my Mirth channel. But the hk_id value i get back is either null or empty string.

Things I've tried:

  1. use the function re.match() but this gives me error, mirth says cannot find function match in object...
  2. I tried to put single quote around the regular expression below, or the /
  3. I tried to reduce my regular expression to a simplest form to test which is re.exec('.*') and yet I still get the empty or null value.
  4. Instead of running RegExp.$1, I tried return m only, but no differences were made.

I think it may boil down to how I escape the characters, but I can't find any Mirth document about this, if you have any insight they will be greatly appreciated.

var hk_id = Find_HKID();
var xml_msg = 
'<?xml version="1.0" encoding="utf-8" ?> <XML><Barcode="'+hk_id+'" /></XML>';

var sResp = ResponseFactory.getSuccessResponse(xml_msg)
responseMap.put('Response', sResp);


function Find_HKID() 
{
   var test = 'HKID:A1234567~PKey:00888880~DOC:TKWC033330'
   var re = new RegExp(test);
   var m = re.exec('.*(HKID:.*?)(.+?)((?=~)|\s|\z)');
   return RegExp.$1 + RegExp.$2 + RegExp.$3 + "";
}
Was it helpful?

Solution

You confused regex and and test string, it should be:

function Find_HKID() 
{
   var test = 'HKID:A1234567~PKey:00888880~DOC:TKWC033330'
   var re = new RegExp('.*(HKID:.*?)(.+?)((?=~)|\s|\z)');
   var m = re.exec(test);
   return RegExp.$1 + RegExp.$2 + RegExp.$3 + "";
}

Now it works like a charm:-D

And btw. you should not use new RegExp(), it's slow and ugly. Use the regex directly:

var re = /.*(HKID:.*?)(.+?)((?=~)|\s|\z)/;

Edit: like Ωmega proposed this regex might work for you too, and is much more precise:

var re = /.*(HKID:.*?)[~\s]/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top