2

Let's say I have this string:

"14 be h90 bfh4"

And I have this regex pattern:

"(\w+)\d"

In PowerShell, how do I get an array with the contents {"h", "bfh"}?

2
  • i am not very good with regex but im trying to learn. Is this what you want? $array = ($string -split '(\s)') -replace '[^a-zA-Z-]','' | SELECT-STRING -Pattern '([A-Z])' Commented Nov 26, 2018 at 5:31
  • Try $result = Select-String '\b(\p{L}+)\d+\b' -Input "14 be h90 bfh4" -AllMatches|%{$_.Matches.Groups[1].Value} Commented Nov 26, 2018 at 9:45

3 Answers 3

2

You want to capture one or more alphabets that are followed by a number, hence the regex for what you want to capture would be this,

[a-zA-Z]+(?=\d)

And the powershell code for same will be this,

$str = "14 be h90 bfh4"
$reg = "[a-zA-Z]+(?=\d)"
$spuntext = $str | Select-String $reg -AllMatches |
            ForEach-Object { $_.Matches.Value }
echo $spuntext

Disclaimer: I barely know powershell scripting language so you may have to tweak some codes.

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

2 Comments

The powershell part does need rework but the gist of it looks good
Thanks @LievenKeersmaekers. I actually just googled about powershell and came up with this. I've never got a chance to use powershell before. But its good, everything has a first time :)
1

A bit shorten version:

@(Select-String "[a-zA-Z]+(?=\d)" -Input "14 be h90 bfh4" -AllMatches).Matches.Value

Comments

1

Multiple ways to skin a cat as demonstrated by the other answers. Yet another way would be by using the [regex] object provided by .Net

$regex = [regex] '([a-z]+)(?=\d+)'
$regex.Matches("14 be h90 bfh4") | Select Value

Comments

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.