Ranges

The hyphen is used to define a range of characters. For example, we might want to match any number repeated one or more times (using +):

'1st place' -match '[0-9]+'    # $matches[0] is "1" 
'23rd place' -match '[0-9]+'   # $matches[0] is "23" 

A range in a character class can be any range of ASCII characters, such as the following examples:

  • a-z
  • A-K
  • 0-9
  • 1-5
  • !-9 (0-9 and the ASCII characters 33 to 47)

The following returns true as " is character 34 and # is character 35 that is, they are within the range !-9:

PS> '"#' -match '[!-9]+'; $matches[0]
True
"#

The range notation allows hexadecimal numbers within strings to be identified. A hexadecimal character can be identified by a character class containing 0-9 and a-f:

PS> 'The registry value is 0xAF9B7' -match '0x[0-9a-f]+'; $matches[0]
True
0xAF9B7

If the comparison operator were case-sensitive, the character class may also define A-F:

'The registry value is 0xAF9B7' -cmatch '0x[0-9a-fA-F]+' 

Alternatively, a range might be used to tentatively find an IP address in a string:

PS> (ipconfig) -match 'IPv4 Address.+: *[0-9]+.[0-9]+.[0-9]+.[0-9]+'
IPv4 Address. . . . . . . . . . . : 172.16.255.30

The range used to find the IP address here is very simple. It matches any string containing four numbers separated by a period, for example, the version number following matches:

'version 0.1.2.3234' -match '[0-9]+.[0-9]+.[0-9]+.[0-9]+' 

This IP address matching regular expressions will be improved as the chapter progresses.

The hyphen is not a reserved character when it is put in a position where it does not describe a range. If it is the first character (with no start to the range), it will be treated as a literal. The following split operation demonstrates this:

PS> 'one-two_three,four' -split '[-_,]'
one
two
three
four

The same output is seen when - is placed at the end (where there is no end to the range):

'one-two_three,four' -split '[_,-]' 

Elsewhere in the class, the escape character may be used to remove the special meaning from the hyphen:

'one-two_three,four' -split '[_-,]' 
..................Content has been hidden....................

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