如何使用正则表达式在字符之间插入空格? [英] How to insert spaces between characters using Regex?

查看:162
本文介绍了如何使用正则表达式在字符之间插入空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试了解有关使用Regex(正则表达式)的更多信息.在C#(VS 2010)中使用Microsoft版本的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"

并将其更改为

"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).

(我已经阅读了其他文章,但是我似乎无法掌握Regex.请客气:)).

(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).

推荐答案

您只能通过正则表达式来执行此操作,而无需内置的c#函数.使用以下正则表达式,然后将匹配的边界替换为空格.

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.

(?<=.)(?!$)

演示

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

说明:

  • (?< =.)正向后方断言,匹配必须以字符开头.
  • (?!$)负向超前,断言匹配不会在行锚的结尾.因此,将匹配所有字符旁边的边界,但不会匹配最后一个字符旁边的边界.
  • (?<=.) 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)(?!$)

演示

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

说明:

  • (?<!^)向后看是负数,表示比赛不会在开始时进行.
  • (\ B | \ b)匹配两个单词字符和两个非单词字符之间的边界( \ B )或匹配两个单词字符之间的边界一个单词字符和一个非单词字符( \ b ).
  • (?!$)负向超前断言匹配不会在行锚的结尾.
  • (?<!^) 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.

这篇关于如何使用正则表达式在字符之间插入空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆