Amy Amy - 1 month ago 8
C# Question

Add space around each / using Humanizer or Regex

I have a string like the following:

var text = @"Some text/othertext/ yet more text /last of the text";


I want to normalize the spaces around each slash so it matches the following:

var text = @"Some text / othertext / yet more text / last of the text";


That is, one space before each slash and one space after. How can I do this using Humanizer or, barring that, with a single regex? Humanizer is the preferred solution.

I'm able to do this with the following pair of regexes:

var regexLeft = new Regex(@"\S/"); // \S matches non-whitespace
var regexRight = new Regex(@"/\S");
var newVal = regexLeft.Replace(text, m => m.Value[0] + " /");
newVal = regexRight.Replace(newVal, m => "/ " + m.Value[1]);

Answer

Are you looking for this:

  var text = @"Some text/othertext/ yet more text /last of the text";

  // Some text / othertext / yet more text / last of the text 
  string result = Regex.Replace(text, @"\s*/\s*", " / ");

slash surrounded by zero or more spaces replaced by slash surrounded by exactly one space.