Replace forward slash with space before and after only if no space in C#

Viewed 300

I have the following input:

aaa/bbb
ccc/ ddd
eee /fff
ggg / hhh
/iii/jjj/

I would like to make sure all forward slashes (Except for the ones in the end of a string) have a space before and after. The result would be:

aaa / bbb
ccc / ddd
eee / fff
ggg / hhh
/iii / jjj/

So far I have the following regex:

(?<=\/)(?!$)

But this is still far from working. Any help would be appreciated figuring out the correct regex for this. The language is C#.

1 Answers

You can use

var output = Regex.Replace(text, @"\s*(?<!^\s*)/(?!\s*$)\s*", " / ", RegexOptions.Multiline);

See the regex demo

Details:

  • \s* - zero or more whitespaces
  • (?<!^\s*) - a negative lookbehind that fails the match if there is start of a line followed with zero or more whitespaces immediately on the left
  • / - a / char
  • (?!\s*$) - a negative lookahead that fails the match if there are zero or more whitespaces followed with end of line position immediately on the right
  • \s* - zero or more whitespaces.

Or, another variation:

var output = Regex.Replace(text, @"(?<=(?<!^)/(?!\s|$))|(?=(?<!^|\s)/(?!$))", " ");

See this regex demo.

Details:

  • (?<=(?<!^)/(?!\s|$)) - a position right after a / that is neither at the start nor at the end of a string and that is not followed with a whitespace
  • | - or
  • (?=(?<!^|\s)/(?!$)) - a position right before a / that is neither at the start nor at the end of a string and that is not preceded with a whitespace.
Related