![]() ![]() ![]() ![]() ![]() ![]() ![]() |
|||||
|
|
|||||
| Pattern variables | |||||
| Prerequisite Concepts | |||||
When using patterns to match sections of input data, you must first capture the data in pattern variables for later use. Pattern variables are assigned using the => symbol, and referenced later. For example, in the first find rule in the following program the matched input data is assigned to the "found-text" pattern variable.
process
submit "Mary had a little [white] lamb"
find ("[" letter+ "]") => found-text
output found-text
find any
This program outputs "[white]".
What if you want to output only the word in the square brackets, but not the brackets themselves? Try this:
process
submit "Mary had a little [white] lamb"
find "[" letter+ => found-text "]"
output found-text
find any
This program outputs "white". Here, the pattern variable is attached only to the part of the pattern immediately preceding the pattern variable assignment. In fact, this is the default behavior of pattern variables. That's why, to make the previous example work correctly, we had to surround the three elements of the pattern with parentheses to ensure that the text matched by the whole pattern was captured.
You can have more than one pattern variable in a pattern. You can even nest them. For example:
process
submit "Mary had a little [white] lamb"
find ("[" => first-bracket
letter+ => found-word
"]" => second-bracket) => found-text
output first-bracket
output found-word
output second-bracket
output found-text
find any
The output of this program would be "[white][white]". The first "[white]" is the result of the first three output actions, and the second the result of the fourth output action.
|
Prerequisite Concepts Pattern matching |
| ---- |