Home > Software design >  Powershell - Need to recognize if there is more than one result (regex)
Powershell - Need to recognize if there is more than one result (regex)

Time:12-03

I am using this to find if file name contains exactly 7 digits

if ($file.Name -match '\D(\d{7})(?:\D|$)') {
    $result = $matches[1]
}

The problem is when there is a file name that contains 2 groups of 7 digits for an example:

patch-8.6.22 (1329214-1396826-Increase timeout.zip 

In this case the result will be the first one (1329214). For most cases there is only one number so the regex is working but I must to recognize if there is more than 1 group and integrated into the if ()

CodePudding user response:

  • The -match operator only ever looks for one match.

  • To get multiple ones, you must currently use the underlying .NET APIs directly, specifically [regex]::Matches():

    • Note: There's a green-lighted proposal to implement a -matchall operator, but as of PowerShell 7.3.0 it hasn't been implemented yet - see GitHub issue #7867.
# Sample input.
$file = [pscustomobject] @{ Name = 'patch-8.6.22 (1329214-1396826-Increase timeout.zip' }

# Note: 
# * If *nothing* matches, $result will contain $null
# * If *one* substring matches, return will be a single string.
# * If *two or more* substrings match, return will be an *array* of strings.
$result = ([regex]::Matches($file.Name, '(?<=\D)\d{7}(?=\D|$)')).Value
  • .Value uses member-access enumeration to extract matching substrings, if any, from the elements of the collection returned by [regex]::Matches().

  • I've tweaked the regex to use lookaround assertions ((?<=/...) and (?=...)) so that only the substrings of interest are captured.

CodePudding user response:

Here is a possible solution:

if ($file.Name -match '\D(\d{7})(?:\D|$)') {
    $results = @()
    for ($i = 1; $i -le $matches.Count; $i  ) {
        $results  = $matches[$i]
    }
}

In this solution, we use a for loop to iterate over all the matches and add each match to the $results array. Then, you can use the $results array to check if there is more than one match.

For example, you can use the Length property of the $results array to check how many matches there are:

if ($results.Length -gt 1) {
    # There is more than one match
}

Alternatively, you can use the Count method of the $results array to check how many matches there are:

if ($results.Count -gt 1) {
    # There is more than one match
}
  • Related