Add space around each / using Humanizer or Regex

I have a line 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 that it matches the following:

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

That is, one place before each slash and one place after. How can I do this with Humanizer or, if not, with one regex? A humanizer is the preferred solution.

I can do this with the following pairs of regular expressions:

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]);
+4
source share
1 answer

You are looking for:

  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*", " / ");

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

+5
source

Source: https://habr.com/ru/post/1659441/


All Articles