regular expression for whitespace in visual studio
Asked Answered
L

1

8

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.

Linseylinseywoolsey answered 5/11, 2014 at 6:15 Comment(2)
The question mark indicates there is zero or one of the preceding element. The concept of regular expressions has nothing to do with Visual Studio. You can read more about it at en.wikipedia.org/wiki/Regular_expression.Ethology
Look for (positive) look ahead.Sabbatarian
C
11

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
Cytogenesis answered 5/11, 2014 at 6:17 Comment(2)
Well it's not his Regex, it's MSDN's msdn.microsoft.com/en-us/library/2k3te2cs.aspxFaun
I guess (?=expression) is the same as (?expression) I should focus on .net regex.Linseylinseywoolsey

© 2022 - 2024 — McMap. All rights reserved.