When I use regular expression to replace white spaces, \s is also matching the end of a line and not just the space in a line. How do I rectify this to just replace the whitespaces in a line.

2

2 Answers

\s stands for any kind of white space, ie. simple space, tabulation, line break...

You can use \h for horizontal space: space or tabulation.

If you want to match only spaces between words, you can use: (?<=\S)\h+(?=\S)

where

  • (?<=\S) is a positive lookbehind that make sure we have a non whitespace before
  • (?=\S) is a positive lookahead that make sure we have a non whitespace after.

You can match on the specific whitespace characters you want, rather than selecting all whitespace characters.

For example, to match one or more spaces and tabs, use [ \t]+. Note the space AND \t characters will be matched.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy