Home > Net >  how to get the value in a string using regex
how to get the value in a string using regex

Time:10-19

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 -match operation returns $true, the automatic $Matches variable reflects what the regex captured, with property (key) 0 containing the full match, 1 the 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:
      • -match only 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.
  • 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, $1 refers 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
      • -replace also supports an array of input strings, in which case each array element is processed separately (-match does too, but in that case it does not populate $Matches).
      • A caveat re -replace is that if the regex does not match, the input string is returned as-is
  • Related