I want to write a regex to match on a string and ignore white spaces. For example, a search for 'foobar' would match on 'foo bar'.
+3
A:
You can strip the spaces in both the pattern and search strings and use indexOf()
if that's acceptable (might be a problem if you don't have enough memory to do so).
I don't think a regex would be a good idea, but you could basically make a pattern like:
/f\s*o\s*o\s*b\s*a\s*r/
Which basically has optional whitespaces in between every character.
NullUserException
2010-09-28 01:46:57
or contains(). +1
Thilo
2010-09-28 01:48:50
Stripping spaces is the way to go. Don't even suggest the regex as an option just because the OP asked for it. :)
casablanca
2010-09-28 01:51:19
@casablanca I said "I don't think a regex would be a good idea," the OP can use it at their own peril ;)
NullUserException
2010-09-28 01:52:16
stripping the white spaces is perfect. Thanks!
NullPointer0x00
2010-09-28 02:15:36
@NullPointer You could [accept the answer](http://meta.stackoverflow.com/questions/16721/what-is-an-accept-rate-and-how-does-it-work/65088#65088) and put this question in the "solved" bin ;-)
NullUserException
2010-09-28 02:27:48
Maybe "I don't think a regex would be a good idea" should have been in bold... and blinking. :)
JoshD
2010-09-28 02:30:48
@Josh It isn't terrible either, because you won't have to create a new string in memory. Java's `String.replace()` uses regex anyways.
NullUserException
2010-09-28 02:59:13
I would probably use a regex (or some other scanner code) if the string to match against was very large (so that I do not want to create a copy of it with whitespace removed).
Thilo
2010-09-28 07:00:46