0

I have a simple REGEX method to obtain the last alphabetic characters of a string by removing letters and numbers which precede it:

"TEST02TEST" | %{($_ -Replace '\D*\d*(\w*)', '$1')}

the output for this is obviously TEST

What if I want to select it at the end of a pipeline? What do I call it, what is it's object name?

Basically I am trying to use add-member get both the refined string and the original string like this:

"TEST02TEST" | %{($_ -Replace '\D*\d*(\w*)', '$1') | Add-Member -MemberType NoteProperty -Name OriginalString -Value $_ -PassThru} | select OriginalString, (something here)

What is the "something here"?

1 Answer 1

3

Supposing you have a series of strings you need to tackle, like:

$strings = "TEST02TEST", "Blah123Something", "xyz0897654ABC"

you could do this:

foreach ($str in $strings) {
    $str | Select-Object @{Name = 'OriginalString'; Expression = {$_}},
                         @{Name = 'LastWordChars';  Expression = {$_ -replace '\D*\d*(\w+)', '$1'}}
}

Output:

OriginalString   LastWordChars
--------------   -------------
TEST02TEST       TEST
Blah123Something Something
xyz0897654ABC    ABC

Instead of @{Name = 'LastWordChars'; Expression = {$_ -replace '\D*\d*(\w+)', '$1'}} you could also use the regex -split operator:

@{Name = 'LastWordChars';  Expression = {($_ -split '\d+')[-1]}}

Of course, the property name 'LastWordChars' is totally up to you.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Theo - this is how that refactors: "TEST02TEST" | % {$_ | Select-Object @{Name = 'OriginalString'; Expression = {$_}}, @{Name = 'LastWordChars'; Expression = {$_ -replace '\D*\d*(\w+)', '$1'}}}
@IanB Yes, but on a single string "TEST02TEST" there is no need to do a ForEach-Object (aka %). This is the case when you are parsing an array of strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.