m0dest0
m0dest0

Reputation: 859

Powershell, getting substring using regular expression and special characters

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 ^" and "^"

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".

Any comments are welcome.

Upvotes: 0

Views: 6093

Answers (3)

Shay Levy
Shay Levy

Reputation: 126912

Two more options:

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

Upvotes: 1

knb
knb

Reputation: 9333

you can also try this:

$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"
}

Upvotes: 2

CB.
CB.

Reputation: 60956

try this:

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

Upvotes: 1

Related Questions