How to insert spaces between characters using Regex?

后端 未结 3 960
花落未央
花落未央 2020-12-16 03:32

Trying to learn a little more about using Regex (Regular expressions). Using Microsoft\'s version of Regex in C# (VS 2010), how could I take a simple string like:

         


        
3条回答
  •  伪装坚强ぢ
    2020-12-16 03:59

    You could do this through regex only, no need for inbuilt c# functions. Use the below regexes and then replace the matched boundaries with space.

    (?<=.)(?!$)
    

    DEMO

    string result = Regex.Replace(yourString, @"(?<=.)(?!$)", " ");
    

    Explanation:

    • (?<=.) Positive lookbehind asserts that the match must be preceded by a character.
    • (?!$) Negative lookahead which asserts that the match won't be followed by an end of the line anchor. So the boundaries next to all the characters would be matched but not the one which was next to the last character.

    OR

    You could also use word boundaries.

    (?

    DEMO

    string result = Regex.Replace(yourString, @"(?

    Explanation:

    • (? Negative lookbehind which asserts that the match won't be at the start.
    • (\B|\b) Matches the boundary which exists between two word characters and two non-word characters (\B) or match the boundary which exists between a word character and a non-word character (\b).
    • (?!$) Negative lookahead asserts that the match won't be followed by an end of the line anchor.

提交回复
热议问题