NottyHead
NottyHead

Reputation: 197

Search Simultaneous Special Characters in a string using PowerShell

I am trying to work on an issue where if a string has multiple "special characters " in a string how do I replace that with a single character. For Example: -

$a = "INC0010347~INC0010348~~INC0010349"
$a = $a.Replace("~~","~")
$a

Result 1: - "INC0010347~INC0010348~INC0010349"

In the above case a Replace function would work if the characters are 2 in number. However anything more than 2 will fail.. as in the below:

$a = "INC0010347~INC0010348~~~INC0010349"
$a = $a.Replace("~~","~")
$a

Result 2: - "INC0010347~INC0010348~~INC0010349"

I am working on a script that would help me do this dynamically irrespective of the number of special characters (in this case tilde(~)) the result should be

Result 1: - "INC0010347~INC0010348~INC0010349"

Upvotes: 0

Views: 108

Answers (1)

Avshalom
Avshalom

Reputation: 8889

Just add the + Quantifier:

$a = "INC0010347~INC0010348~~~INC0010349"
$a -replace '~+','~'

Or:

[regex]::Replace($a,'~+','~')

Note:

instead of using string.Replace method e.g. $a.Replace('~+','~') which will not work, use -replace or [regex]::Replace which support Regex

See:

Quantifiers in Regular Expressions

Upvotes: 3

Related Questions