-1

How to replace duplicate spaces into HTML tags by regex?

The example:

<span      class    ="html-attribute-value">some long        text    with 
spaces           </span>

I want to:

<span class ="html-attribute-value">some long        text    with 
spaces           </span>
Ultra
  • 21
  • 6

1 Answers1

0

regex with a little c#:

public class Program
{
    public static void Main()
    {
        Console.WriteLine(removeTwoSpaces(@"<span      class    ='html - attribute - 
        value'>some long        text    with 
        spaces </ span > "));
    }

    public static string removeTwoSpaces(string value)
    {            
        return Regex.Replace(value, @"(?<prefix><[^\s]*)(?<loop>(?<space>\s{2,}).*?)*(?<postfix>>(.|\n)*)", (matche) =>
         {
             string ret = string.Empty;
             var prefix = matche.Groups["prefix"].Value;
             ret += prefix;
             var loops = matche.Groups["loop"].Captures;
             var spaces = matche.Groups["space"].Captures;
             for (int i = 0; i < loops.Count; i++)
             {
                 ret += loops[i].Value.Replace(spaces[i].Value, " ");
             }
             var postfix = matche.Groups["postfix"].Value;
             ret += postfix;
             return ret;
         });
    }
}
s-s
  • 224
  • 1
  • 10