Regular expression: find spaces (tabs/space), but not newlines

How can I have a regular expression that tests for spaces or tabs, but not newlines?

I tried \s, but I found out that it tests for newlines too.

I use C# (.NET) and WPF, but it shouldn't matter.

244773 次浏览

使用字符类: [ \t]

试试这个字符集:

[ \t]

This does only match a space or a tabulator.

注意: 对于那些处理 CJK文本(中文、日文和韩文)的人来说,对于我到目前为止尝试过的任何实现(Perl,。NET、 PCRE和 Python)。您需要首先规范化字符串(比如用 \u0020替换所有的 \u3000) ,或者必须使用一个字符集,除了目标空白(比如 [ \t\u3000])之外,还包含这个代码点。

如果您使用的是 Perl 或 PCRE,则可以选择使用 水平空格水平空格\h简写,其中似乎包括单字节空间、双字节空间和制表符等。有关更多细节,请参见 匹配空格但不匹配换行(Perl)问题。

然而,这个 \h速记还没有在.NET 和 C # 中实现,就我所知。

作为 Eiríkr Útlendi 注意到,公认的解决方案只考虑两个空格字符: 水平选项卡(U+0009)和中断空格(U + 0020)。它不考虑其他空白字符,比如非中断空格(正好在我要处理的文本中)。

A more complete white space character listing is included on Wikipedia and also referenced in the 链接的 Perl 答案. A simple C# solution that accounts for these other characters can be built using 字符类减法字符类减法:

[\s-[\r\n]]

或者,包括 Eiríkr Útlendi 的解决方案,你得到

[\s\u3000-[\r\n]]

如果你想替换 空间,下面的代码在 C # 中对我很有用。

Regex.Replace(Line, "\\\s", "");

For Tab

Regex.Replace(Line, "\\\s\\\s", "");