How to ignore whitespace in a regular expression subject string?

Steven picture Steven · Jan 4, 2011 · Viewed 228.6k times · Source

Is there a simple way to ignore the white space in a target string when searching for matches using a regular expression pattern? For example, if my search is for "cats", I would want "c ats" or "ca ts" to match. I can't strip out the whitespace beforehand because I need to find the begin and end index of the match (including any whitespace) in order to highlight that match and any whitespace needs to be there for formatting purposes.

Answer

Sam Dufel picture Sam Dufel · Jan 4, 2011

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/