Paulo Bueno
Paulo Bueno

Reputation: 2569

How to remove duplicate char on string (more than 3 occurences) using Regex on VB.Net?

I'm sorry if it's a duplicate of some question but this is specific on Vb.Net Regex function.

I need to remove any occurrence of 3 or more duplicate characters on a given string. For example:

Dim strTmp As String = "111111.......222222 and 33"
Dim output As String = Regex.Replace(strTmp, "????", "")

Debug.Print(output)

The "????" part I guess should be the Regex expression, which I must assume I know almost nothing about.

I don't know if that's the correct syntax. But I need the output to come as:

"1.2 and 33"

So any directions is appreciated.

Upvotes: 3

Views: 4253

Answers (1)

Oded
Oded

Reputation: 499212

This will produce the required result:

Dim output As String = Regex.Replace("111111.......222222 and 33", 
                                     @"(.)\1{2,}", 
                                     "$1")

output will contain "1.2 and 33".

Breakdown:

(.)   - Match any single character and put in a capturing group
\1    - Match the captured character
{2,}  - Two or more times

Note that the replacement is $1 - this is a variable that stands for the result of the first captured group.

Upvotes: 12

Related Questions