tags:

views:

41

answers:

1

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
or contains(). +1
Thilo
Stripping spaces is the way to go. Don't even suggest the regex as an option just because the OP asked for it. :)
casablanca
@casablanca I said "I don't think a regex would be a good idea," the OP can use it at their own peril ;)
NullUserException
stripping the white spaces is perfect. Thanks!
NullPointer0x00
@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
Maybe "I don't think a regex would be a good idea" should have been in bold... and blinking. :)
JoshD
@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
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