als9xd
als9xd

Reputation: 854

Replace word and remove extra spaces

I'm using the following code to replace ampersands with "and"s. The problem I have is when I have multiple ampersands next to each other I end up with two spaces between the "and"s ("-and--and-" instead of "-and-and-"). Is there a way I can combine the bottom two regex replaces into a single one while only removing duplicate spacing between ampersands?

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var replacedWord = Regex.Replace("&&", @"\s*&\s*", " and ");
        var withoutSpaces = Regex.Replace(replacedWord, @"\s+and\s+", " and ");
        Console.WriteLine(withoutSpaces);
    }
}

Upvotes: 0

Views: 105

Answers (2)

JohnyL
JohnyL

Reputation: 7142

string input = "some&very&&longa&&&string";
string pattern = "&";
string x = Regex.Replace(input, pattern, m =>(input[m.Index-1] == '&' ? "": "-") + "and-");

Upvotes: 0

NetMage
NetMage

Reputation: 26917

Using a String extension method for repeating,

public static string Repeat(this string s, int n) => new StringBuilder(s.Length * n).Insert(0, s, n).ToString();

You can use the lambda (delegate) version of Regex.Replace:

var withoutSpaces = Regex.Replace("a&&b", @"(\s*&\s*)+", m => " "+"and ".Repeat(m.Groups[1].Captures.Count));

Upvotes: 2

Related Questions