9.2. Templates Containing String Patterns
A string pattern matches characters in the source string to indicate where to split it. A string pattern can be either of the following:
- Literal string pattern
One or more characters within quotation marks.
- Variable string pattern
Here are two templates, a simple template and a template containing a literal string pattern:
var1 var2 /* simple template */
var1 ", " var2 /* template with literal string pattern */
The literal string pattern is: ", "
. This template puts characters:
From the start of the source string up to (but not including) the first character of the match (the comma) into var1
Starting with the character after the last character of the match (the character after the blank that follows the comma) and ending with the end of the string into var2
A template with a string pattern can omit some of the data in a source string when assigning data to variables. The next two examples contrast simple templates with templates containing literal string patterns.
Example 9.7. Template string patterns
/* Simple template */
name="Smith, John"
parse var name ln fn /* Assigns: ln="Smith," */
/* fn="John" */
Notice that the comma remains (the variable ln
contains "Smith,"
). In the next example the template is ln ", " fn
. This removes the comma.
Example 9.8. Template string patterns
/* Template with literal string pattern */
name="Smith, John"
parse var name ln ", " fn /* Assigns: ln="Smith" */
/* fn="John" */
First, the language processor scans the source string for ", ". It splits the source string at that point. The variable ln
receives data starting with the first character of the source string and ending with the last character before the match. The variable fn
receives data starting with the first character after the match and ending with the end of string.
A template with a string pattern omits data in the source string that matches the pattern. (There is a special case (see
Section 9.8.2, “Combining String and Positional Patterns”) in which a template with a string pattern does not omit matching data in the source string.) The pattern
", "
(with a blank) is used instead of
","
(no blank) because, without the blank in the pattern, the variable
fn
receives " John" (including a blank).
If the source string does not contain a match for a string pattern, any variables preceding the unmatched string pattern get all the data in question. Any variables after that pattern receive the null string.
A null string is never found. It always matches the end of the source string.