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.

Answers


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

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

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

Need Your Help

How can I check for text that will display with @Html.ValidationSummary() and then modify a message?

asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

I am using @Html.ValidationSummary() on my registration page. If the user name entered is already used I get the following message HTML:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.