4.09 IN and LIKE

The operator IN

IN operator is used to test if the needle(left-value) is contained in the haystack(right-value). It returns the position in the string if found or 0 if not.

// Using IN with strings
put "na" in "abcde"         // displays 0
put "bc" in "abcde"         // displays 2
put 12 in "234"             // displays 0
put 25 in "341256"          // displays 4
put 12 in "34125612"        // displays 3

If the haystack is numeric IN does a simple equality test.

// Using IN with number (true only if left = right)
put 11 in 21                // displays 0
put 11 in 11                // displays 1
put 11 in 211               // displays 0

IN can also be used to find an element in an array. The value returned is the index of the element.

// Using IN with arrays
put 1 in {2,3}              // displays 0
put 1 in {1,2}              // displays 1
put 2 in {1,2}              // displays 2
put "c" in {"a", "b", "c"}  // displays 3

The operator LIKE

LIKE is a regular-expression operator. It compares the left part of the expression with the pattern (right part) and returns 1 if there is a pattern match or 0 if not.

Currently only a subset of the regular expression code is used, based on an excellent old stuff by J. Kercheval (match.c, public-domain, 1991).

To be implemented. There is an option to use PCRE (Perl-Compatible Regular Expression library). (see OPTION).

LIKE uses the same rules as the FILES command and FILES() function.

In the pattern string:

*
matches any sequence of characters (zero or more)
?
matches any character
[SET]
matches any character in the specified set,
[!SET] or [^SET]
matches any character not in the specified set.

A set is composed of characters or ranges; a range looks like character hyphen character (as in 0-9 or A-Z). [0-9a-zA-Z_] is the minimal set of characters allowed in the [..] pattern construct.

put "Hello" like "*"        // displays 1
put "Hello" like "*[oO]"    // displays 1
put "Hello" like "He??o"    // displays 1
put "Hello" like "hello"    // displays 0
put "Hello" like "[Hh]*"    // displays 1

If the search string is numeric it is converted to a string first.

put 123 like "*3"           // displays 1
put 123 like "*23"          // displays 1
put 123 like "1?3"          // displays 1
put 123 like "[12]*"        // displays 1
put 123 like "[89]*"        // displays 0

To include any of '[]*?!^-\' as a match and suppress them as syntax characters precede the character with a '\'.

LIKE can also be used with an array. See 5.06 Array Searching.


lynplex/lp0409.txt · Last modified: 2012/09/08 15:06 (external edit)