Repeating groups

Groups may be repeated using any of the quantifiers. The regular expression that tentatively identifies an IP address can be improved using a repeated group. The starting point for this expression is as follows:

[0-9]+.[0-9]+.[0-9]+.[0-9]+ 

In this expression, the [0-9]+ term followed by a literal . is repeated three times. Therefore, the expression can become as follows:

([0-9]+.){3}[0-9]+ 

The expression itself is not very specific (it will match much more than an IP address), but it is now more concise. This example will be taken further later in this chapter.

If * is used as the quantifier for the group, it becomes optional. If faced with a set of version numbers ranging in formats from 1 to 1.2.3.4, a similar regular expression might be used:

[0-9]+(.[0-9]+)* 

The result of applying this to a number of different version strings is shown in the following code:

PS> 'v1', 'Ver 1.000.232.14', 'Version: 0.92', 'Version-7.92.1-alpha' |
Where-Object { $_ -match '[0-9]+(.[0-9]+)*' } |
ForEach-Object { $matches[0] }
1
1.000.232.14
0.92
7.92.1

In the case of the last example, -alpha is ignored; if that were an interesting part of the version number, the expression would need to be modified to account for that.

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

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