How to run javascript Regular Expression in Mirth
-
13-07-2021 - |
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:
- use the function
re.match()
but this gives me error, mirth sayscannot find function match in object...
- I tried to put single quote around the regular expression below, or the
/
- 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. - 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 + "";
}
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 + "";
}
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