Skip to content

function /(?<val>\d+)(?<timeUnit>)/([int]$val, [string]$timeUnit) { ... } #10042

@Bartolomeus-649

Description

@Bartolomeus-649

Wouldn't it be cool if this or something similar would be possible...

# https://regex101.com/r/EpiXHF/2
[regex]$regEx = @"
(?mx-i)
^
    (?<amount>\d+)
    (?<unit>
        (?: [s]    (?:econd  )? ) |
        (?:        (?:Second )  ) |
        (?: [M]    (?:inute  )? ) |
        (?:        (?:minute )  ) |
        (?: [h]    (?:our    )? ) |
        (?:        (?:Hour   )  ) |
        (?: [Dd]   (?:ay     )? ) |
        (?: [Ww]   (?:eek    )? ) |
        (?: [m]    (?:onth   )? ) |
        (?:        (?:Month  )  ) |
        (?: [Yy]   (?:ear    )? )
    )(?:(?<=[\D]{3})[s])?
    (?<direction> [Aa]go)
$
"@


function $regEx([int]$amount, [string]$unit, [string]$direction)
{
    if($direction.ToLower() -eq "ago")
    {
        $amount = $amount*-1;
    }
    else
    {
        throw "Unsupported direction: $direction";
    }

    [DateTime]$now = Get-Date;
    [DateTime]$result;
    switch -Regex ($unit)
    {
         "(?x-i) s | (?i) second" {$result = $now.AddSeconds($amount);}
         "(?xi)  M | (?i) minute" {$result = $now.AddMinutess($amount);}
         "(?x-i) h | (?i) hour" {$result   = $now.AddHours($amount);}
         "(?xi)  d | (?i) days" {$result   = $now.AddDays($amount);}
         "(?xi)  w | (?i) week" {$result   = $now.AddDays($amount*7);}
         "(?x-i) m | (?i) month" {$result  = $now.AddMonths($amount);}
         "(?xi)  y | (?i) year" {$result   = $now.AddYears($amount);}
        Default {throw "Unsupported unit: $unit"}
    }

    return $result;
}


Proposed technical implementation details (optional)

Perhaps something along this way...

  1. Give the function a unique internal name just to keep track of it
  2. As a last step, when no other function, cmdLet, application or whatever is found, then use the regEx on the potential command and see if it match.
  3. If it match...
    1. make a temporary copy of the function from step 1 (or assign it an alternative name or something)
    2. Name the temporary copy in such a way that it would have ben executed if it had existed as a "normal function"
    3. Call this new temporary function, with the named capture groups from the regex as it's input parameters
  4. cleanup and remove all temporary stuff

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-No ActivityIssue has had no activity for 6 months or moreWG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions