Optional Whitespace Regex

Add a \s? if a space can be allowed.

\s stands for white space

? says the preceding character may occur once or not occur.

If more than one spaces are allowed and is optional, use \s*.

* says preceding character can occur zero or more times.

'#<a href\s?="https://stackoverflow.com/questions/14293024/(.*?)" title\s?="https://stackoverflow.com/questions/14293024/(.*?)"><img alt\s?="https://stackoverflow.com/questions/14293024/(.*?)" src\s?="https://stackoverflow.com/questions/14293024/(.*?)"[\s*]width\s?="150"[\s*]height\s?="https://stackoverflow.com/questions/14293024/(.*?)"></a>#'

allows an optional space between attribute name and =.

If you want an optional space after the = also, add a \s? after it also.

Likewise, wherever you have optional characters, you can use ? if the maximum occurrence is 1 or * if the maximum occurrence is unlimited, following the optional character.

And your actual problem was [\s*] which causes occurrence of a whitespace or a * as characters enclosed in [ and ] is a character class. A character class allows occurrence of any of its members once (so remove * from it) and if you append a quantifier (?, +, * etc) after the ] any character(s) in the character class can occur according to the quantifier.

Leave a Comment