Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...