¿Cómo filtrar cadenas en PowerShell?

Resuelto Techno asked hace 8 meses • 0 respuestas

tengo cadenas:

"C0.test.trd.co"
"C1.trd.co"
"C2.test.trd.co"

etc. Quiero reemplazar las cadenas después de "C0", "C1", "C2", etc. en powerhsell.

Si termina en "trd.co" o "test.trd.co", entonces debería ser "prod.trd.co". En un ejemplo después de la conversión:

"C0.prod.trd.co"
"C1.prod.trd.co"
"C2.prod.trd.co"

Gracias.

Techno avatar Feb 16 '24 19:02 Techno
Aceptado

Podrías usar el patrón (?<=C[0-9]\.)(?:test\.trd\.co|trd\.co)y, si la cadena coincide con ese patrón, reemplazarla con prod.trd.co. Si los dígitos que vienen después Cpueden ser más de 1, puede agregar un +después [0-9]: (?<=C[0-9]+\.)....

'C0.test.trd.co',
'C1.trd.co',
'C2.test.trd.co' -replace '(?<=C[0-9]\.)(?:test\.trd\.co|trd\.co)', 'prod.trd.co'

Consulte https://regex101.com/r/Uplfbm/1 para obtener detalles sobre las expresiones regulares.

Santiago Squarzon avatar Feb 16 '2024 12:02 Santiago Squarzon

Utilice expresiones regulares: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-7.4

Este script imprime las nuevas cadenas basadas en los patrones reemplazados. Puede ampliar esto escribiendo en un archivo, guardando en una variable, etc.

# Define here your input strings
$strings = @(
    "C0.test.trd.co",
    "C1.trd.co",
    "C2.test.trd.co",
    "C3.trd.co"
)

# Define the regex expression. If it starts with "anything.TEST" and/or ends with ".trd.co"
$pattern = "^C\d+(\.test)?\.trd\.co$"

# Loop through each input string
foreach ($string in $strings) {
    # Check if the string matches the pattern
    if ($string -match $pattern) {
        # Replace the input strings if matches with the pattern (So this will replace the "anything.test.trd.co" and the "anything.trd.co")
        $newString = $string -replace "\.test\.trd\.co|\.trd\.co", ".prod.trd.co"
        Write-Output $newString
    } else {
        Write-Output "String doesn't match the pattern: $string"
    }
}
KKI avatar Feb 16 '2024 12:02 KKI