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