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

How can I get a regex that checks for spaces or tabs, but not newlines. I tried \s , but found out that it is also testing newlines.

I use C # / WPF, but that doesn't matter.

+76
regex
Aug 27 '10 at 10:02
source share
5 answers

Using character classes: [ \t]

+152
Aug 27 '10 at 10:03
source share

Try this character set:

 [ \t] 

This matches only a space or tab.

+29
Aug 27 2018-10-10T00:
source share

As @ Eiríkr Útlendi noted, only two space characters are taken into account in the decision: horizontal tab (U + 0009) and space (U + 0020). It does not account for other whitespace characters, such as inextricable spaces (which are in the text I'm trying to figure out). A more complete list of whitespace is included on Wikipedia and is also listed in the related Perl answer . A simple C # solution that takes these other characters into account can be built using a character class subtraction

 [\s-[\r\n]] 

or, including the Eiríkr Útlendi solution, you get

 [\s\u3000-[\r\n]] 
+14
Jun 27 '16 at 13:11
source share

Note. . For those dealing with CJK text (Chinese, Japanese, and Korean), double-byte space (Unicode \u3000 ) is not included in \s for any implementation I have tried so far (Perl, .NET, PCRE, Python). First you need to either normalize your lines first (for example, replacing all \u3000 with \u0020 ), or you will have to use a character set that includes this code in addition to any other space you are targeting, for example [ \t\u3000] .

If you use Perl or PCRE, you have the option of using the shorthand string \h for horizontal spaces, which appears to include single-byte space, double-byte space, and a tab, among others. For more information, see Match without spaces, but not newlines (Perl) .

However, this shorthand \h not implemented for .NET and C # as far as I could tell.

+3
Apr 19 '16 at 21:17
source share

If you want to replace the space below the code, it works for me in C #

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

For tab

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

0
Jul 18 '19 at 5:22
source share



All Articles