4

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]);

1 Answers1

5

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.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    A slower alternative is `Regex.Replace(str, @"(?<=\S)(?=/)|(?<=/)(?=\S)", " ")`, regexhero.net benchmark shows it is 2.5 times slower. Still, does the similar job: finds places where `/` is preceded/followed with a non-whitespace and adds a space there. If the taks was to keep existing spaces, this one would be preferable, but for normalizing, `\s*/\s*` is the one that should be used. – Wiktor Stribiżew Oct 31 '16 at 20:04
  • I want to wait a few hours to see if a Humanizer solution pops up. If none does, I intend to mark this as the accepted answer. –  Oct 31 '16 at 20:40