Vishwa
Vishwa

Reputation: 81

How to remove extra commas in string?

Can anyone please help me to remove extra commas from string and pass them to another string in well formatted to send an email from PowerShell.

$emails = "[email protected],,,[email protected],[email protected],,"

I'm expecting string like below

$emailsTo = "[email protected],[email protected],[email protected]"

Upvotes: 1

Views: 2380

Answers (3)

mklement0
mklement0

Reputation: 440471

To complement the existing, helpful answers:

A more efficient and concise reformulation of Esperento57's answer:

> ',,[email protected],,,[email protected],[email protected],,' -split ',' -ne '' -join ','
[email protected],[email protected],[email protected]

An alternative approach using the .NET Framework directly, via the [string] type's .Split() method with the RemoveEmptyEntries option:

> $emails = ',,[email protected],,,[email protected],[email protected],,'
> $emails.Split(',', [StringSplitOptions]::RemoveEmptyEntries) -join ','
[email protected],[email protected],[email protected]

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200523

Use the -replace operator to collapse consecutive commas to a single one and remove leading/trailing commas from beginning and end of the string:

$emails   = '[email protected],,,[email protected],[email protected],,'
$emailsTo = $emails -replace ',+', ',' -replace '^,|,$'

Upvotes: 3

Esperento57
Esperento57

Reputation: 17492

try this

 $emails = ("[email protected],,,[email protected],[email protected],," -split "," | where{$_ -ne ""}) -join ","

Upvotes: 1

Related Questions