'converting javascript "new RegExp" into powershell [regex]::new()

how would i implement the following javascript code snippet in powershell?

String.prototype.regexCount = function (pattern) {
    if (pattern.flags.indexOf("g") < 0) {
        pattern = new RegExp(pattern.source, pattern.flags + "g");
    }
    return (this.match(pattern) || []).length;
};

I'm thinking its something like this:

$regexCount = { 
    param(
        $pattern
    )
    # ??????
    if ($pattern.flags.indexOf("g") -lt 0) {
        # ????
        # $pattern = new RegExp(pattern.source, pattern.flags + "g");
        $pattern = [regex]::new($pattern)
    }
    # ????
    return ($this.match($pattern) || []).length;
}

I have almost the entire script converted into powershell except for this little nugget of code... Actually, i'm a little bit clueless when javascript starts creating lambda functions with regular expression objects...

for instance what's the significants of string.prototype.somename? wouldn't you just save the lambda to any variable name?



Solution 1:[1]

Using Update-TypeData, create a type-level ScriptMethod ETS member for the .NET string type (System.String):

Update-TypeData -TypeName System.String -MemberName RegexCount -MemberType ScriptMethod  -Value {
  param([regex] $Regex)
  $Regex.Matches($this).Count
}

Now you can call the .RegexCount() method on any string instance, analogous to what your JavaScript code does.

Sample call:

'foo'.RegexCount('.') # -> 3

That is, 3 matches for regex . were found in the input string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1