I am confused on how to get the number in the string below. I crafted a regex
$regex = '(?s)^. \bTotal Members in Group: ([\d.] ).*$'
I need only the number part 2 inside a long string a line reads Total Members in Group: 2.
My $regex returns me the entire line but what i really need is the number.
The number is random
CodePudding user response:
cls
$string = 'Total Members in Group: 2'
$membersCount = $string -replace "\D*"
$membersCount
One more way:
cls
$string = 'Total Members in Group: 2'
$membersCount = [Regex]::Match($string, "(?<=Group:\s*)\d ").Value
$membersCount
CodePudding user response:
Fors1k's helpful answer shows elegant solutions that bypass the need for a capture group ((...)).
In cases where you do need capture groups, the PowerShell-idiomatic way is to:
either: Use
-match, the regular-expression matching operator with a single input string: if the-matchoperation returns$true, the automatic$Matchesvariable reflects what the regex captured, with property (key)0containing the full match,1the first capture group's match, and so on.$string = 'Total Members in Group: 2' if ($string -match '(?s)^.*\bTotal Members in Group: (\d ).*$') { # Output the first capture group's match $Matches.1 }- Note:
-matchonly ever looks for one match in the input.- Direct use of the underlying .NET APIs is required to look for all matches, via
[regex]::Matches()- see this answer for an example.
- Note:
or: Use
-replace, the regular-expression-based string replacement operator, to match the entire input string and replace it with a reference to what the capture group(s) of interest captured; e.g,$1refers to the first capture group's value.$string = 'Total Members in Group: 2' $string -replace '(?s)^.*\bTotal Members in Group: (\d ).*$', '$1'- Note:
-replace, unlike-match, looks for all matches in the input-replacealso supports an array of input strings, in which case each array element is processed separately (-matchdoes too, but in that case it does not populate$Matches).- A caveat re
-replaceis that if the regex does not match, the input string is returned as-is
- Note:
