Powershell, obteniendo una subcadena usando expresiones regulares y caracteres especiales

I have to extract the user info from this line

"user/data ^`ms\john ^`Lorem Ipsum Lorem ^`Lorem Ipsum Lorem"

The pattern is that the info always comes between "user/data ^"Y "^"

The expected result is "ms\john"

This is my attempt,

$line = "user/data ^`ms\john ^`Lorem Ipsum Lorem ^`Lorem Ipsum Lorem"
if ($line -match "user/data(.*)")
{
    write-host "found: $($matches[1])"
} else {
    Write-Host "no found"
}

I don't know how to add special characters in the regexp and extract "ms\john".

Todos los comentarios son bienvenidos.

preguntado el 23 de diciembre de 12 a las 20:12

3 Respuestas

también puedes probar esto:

$line = "user/data ^`ms\john ^`Lorem Ipsum Lorem ^`Lorem Ipsum Lorem"
if ($line -match "user/data\s+\^`?([^\^]+)")
{
    write-host "found: $($matches[1])"
} else {
    Write-Host "no found"
}

Respondido el 23 de diciembre de 12 a las 22:12

+1, the regexp works fine but if I try to read the line from a text line then a backtick is added, any clues? Thanks, - m0dest0

Dos opciones más:

PS> $il = "user/data ^`ms\john ^`Lorem Ipsum Lorem ^`Lorem Ipsum Lorem"

PS> $il -replace '^user/data\ \^`([^\^]+)\ \^.+$','$1'
ms\john

PS> [regex]::Matches($il,'user/data\s\^`([^\^]+)\s\^').Groups[1].Value
ms\john

Respondido el 26 de diciembre de 12 a las 07:12

it works fine but if I try to read the same line from a text file I get "`ms\john". Notice the rave accent or backtick. +1 - m0dest0

it worked, thanks Shay.Can you please explain why the previous one did not work. - m0dest0

PowerShell expands the backtick inside double quotes. You can see the difference if you execute these too: "^" and '^' - shay levy

prueba esto:

$line = "user/data ^`ms\john ^`Lorem Ipsum Lorem ^`Lorem Ipsum Lorem"
if ($line -match "(?<=\^)(.[^\^]*)")
{
    write-host "found: $($matches[1])"
} else {
    Write-Host "no found"
}

Respondido el 23 de diciembre de 12 a las 20:12

+1, Thanks Christian. The regular expression works fine as I stated however if I try to read the same line from a text file, a rave accent is added at the beginning of the captured string like if the text file is being added an additional character. - m0dest0

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.