How to insert spaces between characters using Regex?

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

"Hello"

      

and change it to

"H e l l o"

      

It can be a string of any letter or symbol, capitals, lowercase letters, etc., and there are no other letters or symbols following or leading this word. (The line consists of only one word).

(I've read other posts, but I can't seem to understand Regex. Please be kind :)).

Thanks for any help on this. (an explanation would be most helpful).

+3


source to share


3 answers


You can do this with just regex, no need for built-in C # functions. Use the following regular expressions and then replace the matching borders with a space.

(?<=.)(?!$)

      

DEMO

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

      

Explanation:

  • (?<=.)

    A positive lookbehind states that the match must be preceded by a character.
  • (?!$)

    Negative lookahead that states that the match will not be followed by the end of the line anchor. This way the borders next to all characters will match, but not the one next to the last character.

OR



You can also use word boundaries.

(?<!^)(\B|b)(?!$)

      

DEMO

string result = Regex.Replace(yourString, @"(?<!^)(\B|b)(?!$)", " ");

      

Explanation:

  • (?<!^)

    Negative lookbehind, which asserts no match at the beginning.
  • (\B|\b)

    Matches a boundary that exists between two word characters and two non-word characters ( \B

    ), or matches a boundary that exists between a word character and a non-word character ( \B

    ).
  • (?!$)

    The negative view states that the end of the line anchor will not follow.
+4


source


Regex.Replace("Hello", "(.)", "$1 ").TrimEnd();

      

Explanation

  • The dot character class matches each character in your "Hello" string.
  • Paratheatation around the dot character is required so that we can refer to the captured character through the notation $n

    .
  • Each captured character is replaced with a replacement string. Our replacement string is "$ 1" (note the space at the end). Here $1

    represents the first captured group in the input, so our replacement string replaces each character with that character plus one space.
  • This method will add one space after the final "o", so we call TrimEnd () to remove it.


A demo can be seen here .

For the enthusiast, the same effect can be achieved with LINQ using this one-liner:

String.Join(" ", YourString.Select(c => c))

      

+5


source


It's very simple. To match any character, use a .

period and then replace it with a character along with one extra space

Here brackets (...)

are used for grouping that can be accessed$index

Find what: "(.)"

Give up "$1 "

DEMO

+1


source







All Articles