Many times, you may have the need to determine if a specific pattern exists within a string. To accomplish this, Tcl provides the match
keyword. Let's look at the syntax and then I will explain the major differences and the real strength of this keyword.
The string
syntax is as follows:
string match -nocase pattern string
When invoked with the match
keyword, the string
command will attempt to locate the pattern specified.
The following details the various methods in which the pattern can be passed and illustrates the special characters the pattern can store.
Special Characters |
Description |
---|---|
|
Matches any sequence within the string, including null strings. |
|
Matches any single character in the string. |
|
Matches any character in the set provided. If |
|
Matches the character specified in This avoids interpretation of the *, [], or in the pattern as special characters. |
What these special characters allow us to accomplish is to locate a pattern within a string using wildcards and ranges. In the following example, we will determine if a specific pattern exists within a string. Return values from the commands are provided for clarity. Enter the following command:
% string match a??12? abc123
1
Tcl has returned a value of 1
to indicate that the pattern was located. Try running this again with a single *
instead of the double ?
characters. The string
command scans the string provided and attempts to locate the pattern. If the pattern is located, 1
is returned; if not, the return value is 0
.
3.135.213.212