Locating a pattern within a string

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.

[characters]

Matches any character in the set provided.

If chars contains a sequential notation of the form a-f, then any characters between a and f (a and f inclusive) will result in a match.

x

Matches the character specified in x.

This avoids interpretation of the *, [], or in the pattern as special characters.

How to do it…

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

How it works…

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.213.212