0

I'm looking for a quick PowerShell one-liner to split a string like this:

"123.456,789 101-202_303%404..505(606)      707 a bunch of text 808 %%%*&#!@#$%^&*() 909"

into an array like this:

(123,456,789,101,202,303,404,505,606,707,808,909)

Basically, anytime two numbers are separated by anyting except a number, then consider those to be two separate numbers.

I have searched online for a solution but haven't quite found what I'm looking for.

3
  • 2
    Try $str -split '\D'. \D is regex for "anything that is not a digit". If you suspect more than one non-digit in between, use \D+ Commented Jan 29, 2019 at 21:54
  • That was very close, it added extra results for each space, but that can be resolved by doing this -split '\D' | Where-Object{$_ -ne ""} | sort -Unique. Feel free to make that an answer. Commented Jan 29, 2019 at 21:59
  • Why was this downvoted? Commented Jan 30, 2019 at 14:26

3 Answers 3

3

I'm on a phone right now, so I won't be doing much typing..

$str -split '\D+' | Sort-Object -Unique

Should do it.


In addition to this, after the -split, the elements (although numbers) are still strings. Doing the above sort will therefore sort alphanumeric, not numeric. Since in the example all numbers have three digits, the sort will look fine, but if there are numbers in there with less or more digits, you'll see what I mean:

Lets say your string looks like this:

$str = "123.456,789;12 101-202_303%404..505(606)  7    707 a bunch of text 808 %%%*&#!@#$%^&*() 909"

Splitting and sorting will give you an array like:

101
12
123
202
303
404
456
505
606
7
707
789
808
909

If you change the Sort-Object just a little to become this:

$str -split '\D+' | Sort-Object -Property {[int]$_} -Unique

The output will be sorted Numeric so the result is this:

7
12
101
123
202
303
404
456
505
606
707
789
808
909

Of course, joining the elements after this to become a comma delimited string is as easy as

($str -split '\D+' | Sort-Object -Property {[int]$_} -Unique) -join ','

Output:

7,12,101,123,202,303,404,456,505,606,707,789,808,909
Sign up to request clarification or add additional context in comments.

Comments

0
$x = "123.456,789 101-202_303%404..505(606)      707 a bunch of text 808 %%%*&#!@#$%^&*() 909"
$y = $x -split '[^\d]+(?=\d+)'

Result:

$y -join ','  #   123,456,789,101,202,303,404,505,606,707,808,909

Comments

0

You can use regex to get replace all none digits and then clear empty array parts

"123.456,789 101-202_303%404..505(606)      707 a bunch of text 808 %%%*&#!@#$%^&*() 909" -split '\D' | ?({ $_ -ne "" })

Comments

Your Answer

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