去除一个空格的正则表达式 [英] Regular expression for removing one space

查看:160
本文介绍了去除一个空格的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是去除ONE空间正则表达式?
例如:

  ^ hèL LØW 0 R L迪涅>你好世界



(注意,还是有在世界您好之间有一个空格,它有两个空间之间开头)



通知你,我用C#正则表达式的工作:
之前我做了这样的事情,但它不会对上述情况下正常工作

 正则表达式=新的正则表达式(@[] {2}); 
pattern.Replace(内容,@)


解决方案

要从一个或空间的所有组中删除一个空间,使用

 模式= Regex.Replace(内容,( *),$ 1); 

要更改的 N 的空格楼( N / 2)的空间,用

 模式= Regex.Replace(内容,(?),$ 1); 



我试图添加的例子,但计算器巩固空白,即使在内嵌代码跨越它似乎。






说明,按要求:首先找到一个空间后跟零个或多个空格,并与零个或多个空格替换它,减少了长度由1。第二查找各组中的一个或两个空间和由零个或一个空格替换它,在一种替换中一个替换改变1至0,2至1,3至2两个替换,等等。

What is the regular expression for removing ONE space? e.g:

H e l l o  W o r l d  ---->  Hello World

(Notice that there's still one space in between Hello World. It has two space in between to begin with)

FYI, I'm working with C# regex: Previously I did something like this, but it doesn't work properly for the above case:

Regex pattern = new Regex(@"[ ]{2,}");
pattern.Replace(content, @" ")

解决方案

To remove one space from all groups of one or spaces, use

pattern = Regex.Replace(content, " ( *)", "$1");

To change n spaces to floor(n/2) spaces, use

pattern = Regex.Replace(content, " ( ?)", "$1");

I tried to add examples but stackoverflow consolidates whitespace even in inline code spans it seems.


Explanation, as requested: The first finds a space followed by zero or more spaces and replaces it with the zero or more spaces, reducing the length by 1. The second finds each group of one or two spaces and replaces it by zero or one spaces, changing 1 to 0 in one replacement, 2 to 1 in one replacement, 3 to 2 in two replacements, etc.

这篇关于去除一个空格的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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