Regular expression for a line with only white spaces

I had this requirement to check whether the input string contains only white spaces. I am not a regular RegEx user, so it took me some time to achieve this.

^[ \t\r\n]*$

That’s it. The meaning of the above pattern is [Beginning of line] [0 or multiple white spaces] [End of line]. Note that this pattern matches an empty string also, since we have given * after white spaces. If you want to strictly look for white spaces and exclude empty strings, then change the * to +.

This is not such a big deal that it requires a blog post of its own, but I didn’t find this information when I looked for it. So putting this out there for anyone who comes looking for it.

2 thoughts on “Regular expression for a line with only white spaces

  1. irmak says:

    You might want to add space character too :

    ^[ \t\r\n\s]*$

    as it is, your expression only looks for tab and crlf chars.

  2. Нарт Лӏыша says:

    Works for me ^[\t\r\n\s]*$

Leave a comment