Reputation: 45
Quite a stupid question but I can't figure out how to do this....
I get the OS name from Get-ADComputer
, lets say: "Windows Server 2012 R2 Standard".
I am trying to just select the Year within the Build, eg:
"Windows Server 2012 R2 Standard" > 2012
"Windows Server 2019" > 2019
"Windows Server 2008" > 2008
"Windows Server 2008 R2" > 2008
Quite ignorant on Regex...how could I do it?.
Also, is there a good tutorial on Regex for Powershell you can refer me to?
Upvotes: 2
Views: 3687
Reputation: 21488
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.
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.
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.
Upvotes: 7