Case (in)sensitive comparison with VB.NET LIKE operator in runtime (without Option Compare)
Is there anyway to use LIKE operator in VB.NET as case se开发者_运维知识库nsitive or insensitive during runtime? For example use a flag to do case sensitive or insensitive comparisons.
Obviously this can be done by simple converting them into lower case and forcing application to Option Compare Binary
but maybe there is a better way to do this?
I don't think so. However, you should probably not use the Like
operator anyways if case-insensitivity is important - instead, use regular expressions.
Dim re As New System.Text.RegularExpressions.Regex("^.+ough$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
re.IsMatch("rough") ' True
re.IsMatch("tough") ' True
re.IsMatch("rOUGH") ' True
re.IsMatch("ough") ' False
There's a lot to learn, but basically .
is equivalent to ?
, .*
is equivalent to *
, and \d
is equivalent to #
. You have to wrap it in ^
and $
for equivalency, too. Regular expressions are much more powerful and will do what you need.
You should probably add Imports System.Text.RegularExpressions
if you plan to use them a lot. They can be compiled and reused for efficiency, too.
You could provide a custom class to ensure that you get case case-insensitive comparison even if the default settings is Compare Binary
(case sensitive). You can specify the Option Compare
in a code-file:
Option Compare Text
Public Class CaseInsensitiveLikeOperator
Public Shared Function IsLike(str As String, pattern As String) As Boolean
Return str Like pattern
End Function
End Class
Now this works:
Dim isSame = CaseInsensitiveLikeOperator.IsLike("foo", "Fo?") ' True
If your default is Option Compare Text
you could provide two classes to be on the safe side.
Maybe the best option is to learn regex ;-)
精彩评论