DotNetDeveloper
DotNetDeveloper

Reputation: 587

RegEx to replace more than one hyphen with one hyphen in a string? asp.net C#

string inputString = "Flat---Head-----Self-Tap-Scr---ews----3-x-10mm-8pc";
string outputString = "Flat-Head-Self-Tap-Scr-ews-3-x-10mm-8pc";

Upvotes: 2

Views: 162

Answers (3)

Jaeho Song
Jaeho Song

Reputation: 73

Here's my solution

text = "Flat---Head-----Self-Tap-Scr---ews----3-x-10mm-8pc";
while (text.Contains("--"))
{
    text = text.Replace("--", "-");
}

You can also use Split by- and use Join

text = "Flat---Head-----Self-Tap-Scr---ews----3-x-10mm-8pc";
string result = string.Join("-", text.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries));

The second answer isn't my own answer, I got it from this question c# Trim commas until text appears. I wanted to add you more variables :)

Upvotes: 0

Qtax
Qtax

Reputation: 33908

Regex: -+, replace with -. ;)

Upvotes: 2

zellio
zellio

Reputation: 32484

string inputString = "Flat---Head-----Self-Tap-Scr---ews----3-x-10mm-8pc";
string outputString = Regex.Replace(inputString , @"-+", "-", RegexOptions.None);

Upvotes: 4

Related Questions