Matches a regular expression to a string.
Description
$MATCH is a boolean function that returns 1 if string and regexp match, and 0 if string and regexp do not match. By default, matching is case-sensitive.
ObjectScript support for regular expressions consists of the $LOCATE and $MATCH functions:
-
$MATCH matches a regular expression to the full string and returns a boolean indicating whether a match occurred.
-
$LOCATE matches a regular expression to successive substrings of string and returns the location (and, optionally, the value) of the first match.
The Match()Opens in a new tab method of the %Regex.MatcherOpens in a new tab class provides the same functionality. The %Regex.MatcherOpens in a new tab class provides additional functionality for using regular expressions.
Other ObjectScript matching operations use InterSystems IRIS pattern match operators.
Examples
The following example matches a string with a regular expression that specifies that the first character must be an uppercase letter (\p{LU}), followed by at least one additional character (+ quantifier), and that this second character, and all subsequent characters, must be word characters (letters, numbers, or the underscore character) (\w):
SET strng(1)="Assembly_17"
SET strng(2)="Part5"
SET strng(3)="SheetMetalScrew"
SET n=1
WHILE $DATA(strng(n)) {
IF $MATCH(strng(n),"\p{LU}\w+")
{ WRITE strng(n)," : successful match",! }
ELSE { WRITE strng(n)," : invalid string",! }
SET n=n+1 }
The following example returns 1, because the hexadecimal regular expression (hex 41) matches the letter “A”:
WRITE $MATCH("A","\x41")
The following example returns 1, because the specified string matches the format of spaces (\s) and non-space characters (\S) specified in the regular expression:
WRITE $MATCH("A# $ 4","\S\S\s\S\s\S")
The following example returns 1, because the specified date matches the format of digits and literals specified in the regular expression:
SET today=$ZDATE($HOROLOG)
WRITE $MATCH(today,"^\d\d/\d\d/\d\d\d\d$")
Note that this format requires that the day and month each be specified as two digits, so a leading zero is required for values smaller than 10.
The following example returns 1, because each letter in the string is within the corresponding letter range in the regular expression:
WRITE $MATCH("HAL","[G-I][A-C][K-Z]")
The following example specifies an invalid regexp argument. This results in an error, as shown:
TRY {
SET str="abcdef"
WRITE "match=",$MATCH(str,"\p{}"),!
}
CATCH exp {
WRITE !!,"CATCH block exception handler:",!
IF 1=exp.%IsA("%Exception.SystemException") {
WRITE "System exception",!
WRITE "Name: ",$ZCVT(exp.Name,"O","HTML"),!
WRITE "Location: ",exp.Location,!
WRITE "Code: ",exp.Code,!!
WRITE "%Regex.Matcher status:"
SET err=##class(%Regex.Matcher).LastStatus()
DO $SYSTEM.Status.DisplayError(err) }
ELSE {WRITE "Unexpected exception type",! }
RETURN
}