You can match on the string with the following pattern like so:
$year = if( "Windows Server 2019" -match '\d{4}' ){
$matches[0]
}
This works by using the -match
operator to check that a match against a pattern (regex) is found. If the match is found (-match
returns $True
or $False
), you can then use the automatic $matches
array to find what value matches the pattern. $matches[0]
will contain the matched value, any additional elements would signify matching capturing groups as part of more complex expressions.
As for the expression itself, \d
indicates to match on a numeric character and the {4}
is a quantifier, stating that we want to match on exactly 4 of the preceeding character or token.
Of course, if -match
returned $False
above, then $year
would not be set with a value.
Note that the -match
operator does not support global matching if you ever needed to find all occurrences of a pattern in a string.
But what if I need to match on all occurrences of a pattern in a string?
Your use case above doesn't call for this, but if we do need a global matching option, we can use the [Regex]::Matches
method here, which performs a global pattern match on the input string:
$myString = "2019 2018 a clockwork orangutan 2017 2016"
[Regex]::Matches( $myString, '\d{4}' ).Value # => 2019
# 2018
# 2017
# 2016
[Regex]::Matches
returns an array of System.Text.RegularExpressions.Match
objects. The Value
property contains the actual string that matches the pattern, but you can also look at other properties of this object to learn more information as well, such as the which index in the string the pattern match was found in, for example.
A good regex resource
As for "a good tutorial" on regex, I can't recommend one, but I do make use of https://regexr.com/ when writing and testing regular expressions. It doesn't support .NET regex, but you can change the mode to PCRE which works very closely to how .NET regex works. As you write your expressions, it will break your expression down and explain what each character (or special token) means. There is also a decent reference you can use as well.