From the Firebird 2.5 Language Reference, SIMILAR TO
documentation:
SIMILAR TO matches a string against an SQL regular expression pattern.
Unlike in some other languages, the pattern must match the entire
string in order to succeed—matching a substring is not enough.
In other words, the regular expression is multi-line and - given the linked documentation - provides no start/end anchors as those are already implied (but then whole string, not per line), as partial matches are not supported.
The regular expression implementation in Firebird conforms to the SQL standard, which also doesn't define start / end anchors.
Given your requirements, you probably need something like:
'(abc 1001( %)?)|((% )?1001 abc)'
Where ( %)?
means optionally match a space and zero or more of any character. Given the whole string must match, that means it finds either a space or the end of the string, and similar for (% )?
.
You may need to add additional terms if you also need to find this in the middle of a string (but none of your examples suggested that).
Or, a direct equivalent of (^|\s)1001(\s|$)
:
'(%[[:WHITESPACE:]])?1001([[:WHITESPACE:]]%)?'
An earlier version of this answer used (% |)
instead of (% )?
, but given empty terms are not documented nor part of the standard, that is possibly an implementation bug or at best an undocumented feature. Use that at your own risk.