NetRexx overview - Parsing strings

NetRexx Overview, version 1.160 Copyright (c) IBM Corporation, 2000. All rights reserved. © | 10 Feb 2000
[previous | contents | next]

## Parsing strings

The previous section described some of the string-handling facilities available; NetRexx also provides string parsing, which is an easy way of breaking up strings of characters using simple pattern matching.

A parse instruction first specifies the string to be parsed, often taken simply from a variable. This is followed by a template which describes how the string is to be split up, and where the pieces are to be put.

#### Parsing into words

The simplest form of parsing template consists of a list of variable names. The string being parsed is split up into words (sequences of characters separated by blanks), and each word from the string is assigned (copied) to the next variable in turn, from left to right. The final variable is treated specially in that it will be assigned a copy of whatever is left of the original string and may therefore contain several words. For example, in:

      parse 'This is a sentence.'   v1 v2 v3

the variable `v1` would be assigned the value '`This`', `v2` would be assigned the value '`is`', and `v3` would be assigned the value '`a sentence.`'.

#### Literal patterns

A literal string may be used in a template as a pattern to split up the string. For example

      parse 'To be, or not to be?'   w1 ',' w2 w3 w4

would cause the string to be scanned for the comma, and then split at that point; each section is then treated in just the same way as the whole string was in the previous example.

Thus, `w1` would be set to '`To be`', `w2` and `w3` would be assigned the values '`or`' and '`not`', and `w4` would be assigned the remainder: '`to be?`'. Note that the pattern itself is not assigned to any variable.

The pattern may be specified as a variable, by putting the variable name in parentheses. The following instructions:

      comma=','
      parse 'To be, or not to be?'   w1 (comma) w2 w3 w4

therefore have the same effect as the previous example.

#### Positional patterns

The third kind of parsing mechanism is the numeric positional pattern. This allows strings to be parsed using column positions.

[previous | contents | next]

From The NetRexx Language by Mike Cowlishaw, mfc@uk.ibm.com (ISBN 0-13-806332-X, 197pp, Prentice-Hall, 1997).