将数字输入修改为特定的图案格式?

时间:2018-12-03 05:46:37

标签: powershell scripting active-directory windows-scripting

如何制作以下代码来格式化电话号码以将结果输出到: +44 123 456 789 代替 +44 123456789

Function Format-TelephoneNumber {
    Param(
        [Parameter(ValueFromPipeline = $true, Position = 0)]
        [Alias('Number')]
        [string]$TelephoneNumber,
        [Parameter(Position = 1)]
        [string]$DefaultCountryCode = '+44'
    )
    Process {
        $formattedNumber = $TelephoneNumber -replace '[\x09 ]'
        If ($formattedNumber -match '\A(?<CountryCode>\+[1-9]\d|0)(?<Number>\d*)\Z') {
            If ($Matches['CountryCode'] -eq '0') {
                $countryCode = $defaultCountryCode
            }
            Else {
                $countryCode = $Matches['CountryCode']
            }
            $formattedNumber = $countryCode + ' ' + $Matches['Number']
            $formattedNumber
        }
        Else {
            Write-Error "Unable to parse the string '$($number)' as telephone number!"
        }
    }
}

'+33 123456789', '0123456789', '0 123 456 789' | Format-TelephoneNumber

1 个答案:

答案 0 :(得分:2)

像这样的事情应该起作用,只要将值与数组中的某个范围连接起来即可。

var countToColorMap = [Int: [CountedColor]]()

for (color, colorCount) in colorInfo {
    countToColorMap[colorCount, default: [CountedColor]()].append(CountedColor(color: color as! UIColor, colorCount: colorCount))
}

输出:

Function Format-TelephoneNumber {
    Param(
        [Parameter(ValueFromPipeline = $true, Position = 0)]
        [Alias('Number')]
        [string]$TelephoneNumber,
        [Parameter(Position = 1)]
        [string]$DefaultCountryCode = '+44'
    )
    Process {
        $formattedNumber = $TelephoneNumber -replace '[\x09 ]'
        If (-not ([string]::ISNULLOREMPTY($TelephoneNumber))) {
            If ($formattedNumber -match '\A(?<CountryCode>\+[1-9]\d|0)(?<Number>\d*)\Z') {
                If ($Matches['CountryCode'] -eq '0') {
                    $countryCode = $defaultCountryCode
                }
                Else {
                    $countryCode = $Matches['CountryCode']
                }
                $formattedNumber = $countryCode + ' ' 
                $formattedNumber += -join $Matches['Number'][0..2] + ' '
                $formattedNumber += -join $Matches['Number'][3..5] + ' '
                $formattedNumber += -join $Matches['Number'][6..8]
                $formattedNumber
            }
            Else {
                Write-Error "Unable to parse the string '$($number)' as telephone number!"
            }
        }
    }
}

'+33 123456789', '0123456789', '0 123 456 789' | Format-TelephoneNumber