Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for whitespace in visual studio

I'm using regular expressions to help find/replace in Visual Studio 2012.

According to msdn, (?([^\r\n])\s) matches any whitespace character except a line break. But I don't understand how it works in detail.

I only know that [^\r\n] excludes line breaks and \s match any whitespace.

The outside (?) confuses me and I can not find anything about it on msdn. Can someone explain it to me? Or give me a link to consult.

like image 924
fatmouse Avatar asked Nov 05 '14 06:11

fatmouse


1 Answers

Your regex is wrong. It works only if the \s is preceded by a positive or negative lookahead.

(?:(?=[^\r\n])\s)

DEMO

What the above regex means is , match a space character but it wouldn't be \n or \r

Explanation:

(?:                      group, but do not capture:
  (?=                      look ahead to see if there is:
    [^\r\n]                  any character except: '\r' (carriage
                             return), '\n' (newline)
  )                        end of look-ahead
  \s                       whitespace (\n, \r, \t, \f, and " ")
)                        end of grouping

OR

(?:(?![\r\n])\s)

DEMO

You could achieve the same with negative lookahead also.

Explanation:

(?:                      group, but do not capture:
  (?!                      look ahead to see if there is not:
    [\r\n]                   any character of: '\r' (carriage
                             return), '\n' (newline)
  )                        end of look-ahead
  \s                       whitespace (\n, \r, \t, \f, and " ")
)                        end of grouping
like image 112
Avinash Raj Avatar answered Oct 12 '22 20:10

Avinash Raj