Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - How to insert spaces between characters using Regex?

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:

"Hello"

and change it to

"H e l l o"

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

(I have read the other posts, but I can't seem to grasp Regex. Please be kind :) ).

Thanks for any help with this. (an explanation would be most useful).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

DEMO

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

Explanation:

  • (?<!^) Negative lookbehind which asserts that the match won't be at the start.
  • (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 ().
  • (?!$) Negative lookahead asserts that the match won't be followed by an end of the line anchor.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...