6

Let's say I have this string, "%%%%%ABC", I would like to replace all the "%" with just one "%", so it should be "%ABC".

If its "%%%A%%B%%C%%", it should be "%A%B%C%"

How should I do this?

Habib
  • 219,104
  • 29
  • 407
  • 436
Dhinnesh Jeevan
  • 489
  • 2
  • 7
  • 22
  • 2
    And is it just for `%` or do you also have `"###A##B#C"` ? – H H Feb 16 '15 at 15:39
  • So far I'm only dealing with "%". The issue I'm facing is that, I have a program where users can filter values using SQL filter. My program freezes if they enter stuff like "%%%%%%%%ABC" instead of "%ABC", which of course I will convert "%" to ".*" to be regex compliant. – Dhinnesh Jeevan Feb 16 '15 at 15:42

4 Answers4

20

There is a solution with Regex.Replace method:

private static string TruncatePercents(string input)
{
    return Regex.Replace(input, @"%+", "%");
}
dav_i
  • 27,509
  • 17
  • 104
  • 136
Mark Shevchenko
  • 7,937
  • 1
  • 25
  • 29
2

This'll sort it:

    string ProcessText(string s)
    {
       return Regex.Replace(s, @"%+", "%");
    }

Edit Got beaten to the punch, so to make mine slightly different and to offer scope for varying delimeters:

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = ProcessText(textBox1.Text, "%", "#");
    }

    string ProcessText(string s, string delim, string replaceWith)
    {
       return Regex.Replace(s, @""+ delim + "+", replaceWith);
    }
laminatefish
  • 5,197
  • 5
  • 38
  • 70
1

Use this if you want to replace one or more non-word characters with the single same non-word character.

string result = Regex.Replace(str, @"(\W)+", "$1");
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Try regular expression.

        string strTest = "%%%A%%B%%C%%";
        string strPattern = "%+";
        RegexOptions opt = RegexOptions.IgnoreCase;
        var reg = new Regex(strPattern, opt);
        var strReplaceResult = reg.Replace(strTest, "%");

result will be "%A%B%C%"

kcwu
  • 219
  • 2
  • 6