regular expression for whitespace in visual studio

12,410

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
Share:
12,410

Related videos on Youtube

fatmouse
Author by

fatmouse

Updated on June 04, 2022

Comments

  • fatmouse
    fatmouse almost 2 years

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

    According to msdn, (?([^\r\n])\s) match any whitespace character, except line break.

    But i don's understand how it works in detail.

    I only know [^\r\n] exclude line break, \s match any whitespace.

    The outside (?) confuse me, can not find anything about it on msdn.

    Can someone explain it? Or give me a link to consult.

    • barak manos
      barak manos over 9 years
      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.
    • fardjad
      fardjad over 9 years
      Look for (positive) look ahead.
  • Tyress
    Tyress over 9 years
    Well it's not his Regex, it's MSDN's msdn.microsoft.com/en-us/library/2k3te2cs.aspx
  • fatmouse
    fatmouse over 9 years
    I guess (?=expression) is the same as (?expression) I should focus on .net regex.