SEARCH(where,what)
; Search string in a Global or Array
I $G(where)="" Q
I $G(what)="" Q
F S where=$Q(@where) Q:where="" D
. I ((where[what)!(@where[what)) D
.. W where,"=",@where,!
.. W $E(where,$F(where,"("),$L(where)-1),!
Q
To extract the subscript (key or keys, since multiple can exist) I would use $E and $F since would give problems when "(" or ")" are part of the subscript.
W $E(where,$F(where,"("),$L(where)-1)
Tested on GTM.
Normal input:
GTM>ZWR ^ZNAME
^ZNAME("first,last")="Second Street"
^ZNAME("name,surname")="First Street"
GTM>D SEARCH^ZZTEST("^ZNAME","last")
^ZNAME("first,last")=Second Street
"first,last"
GTM>D SEARCH^ZZTEST("^ZNAME","Street")
^ZNAME("first,last")=Second Street
"first,last"
^ZNAME("name,surname")=First Street
"name,surname"
GTM>D SEARCH^ZZTEST("^ZNAME(""first,last"")","Street")
^ZNAME("name,surname")=First Street
"name,surname"
GTM>D SEARCH^ZZTEST("^ZNAME",",sur")
^ZNAME("name,surname")=First Street
"name,surname"
As a bonus you can also use it to search local arrays:
GTM>ZWR ARRAY
ARRAY(1)="Apple"
ARRAY(1,1)="Apple pie"
ARRAY(2)="Orange"
GTM>D SEARCH^ZZTEST("ARRAY","Apple")
ARRAY(1)=Apple
1
ARRAY(1,1)=Apple pie
1,1
GTM>D SEARCH^ZZTEST("ARRAY","pie")
ARRAY(1,1)=Apple pie
1,1
And no problem with invalid inputs:
GTM>K ARRAY
GTM>D SEARCH^ZZTEST("ARRAY","Apple")
GTM>D SEARCH^ZZTEST("ARRAY","")
GTM>D SEARCH^ZZTEST("ARRAY",)
GTM>D SEARCH^ZZTEST("ARRAY")
GTM>D SEARCH^ZZTEST()
GTM>D SEARCH^ZZTEST("^ZDOESNOTEXIST")
Handling "(" and ")" in the subscript:
GTM>ZWR ARRAY
ARRAY("()")=1
ARRAY("1(")=1
ARRAY("1()")="Orange"
ARRAY("1)")="Apple"
GTM>D SEARCH^ZZTEST("ARRAY","()")
ARRAY("()")=1
"()"
ARRAY("1()")=Orange
"1()"
GTM>D SEARCH^ZZTEST("ARRAY","Apple")
ARRAY("1)")=Apple
"1)"